Jad Joubran
Jad Joubran

Reputation: 2579

ui-router without executing controller on every route change

Ui-router sample configuration:

header: {
      templateUrl: 'header.tpl',
      controller: 'HeaderCtrl'
},
sidebar: {
      templateUrl: 'sidebar.tpl',
      controller: 'SidebarCtrl'
},
main: {
    templateUrl: 'main.tpl'
}

The website starts with a login page which only has a main view.
All the other pages in the app require authentication.

Problem: Every time I open a new route, HeaderCtrl and SidebarCtrl are being executed.

Is there a way to make the SidebarCtrl and HeaderCtrl not re-execute on every route change?

Upvotes: 2

Views: 869

Answers (1)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28465

Yes. You can achieve this by implemented nested state. In case of nested state, parent state - controller, directives are executed only once and on change in child state will not execute them again until and unless you want to forcibly execute them.

With nested state just add a parent state let us say "app" with a template which will act as container having header and footer controller - please see these can be directives as well. And a content container having ui-view.

Child states will be like "app.child1", "app.child2", etc.

Please note child state has to start with "app.", because this is the link which defines the parent child relationship w.r.t. ui-router.

In case you are using named views, then updated the child state like this where main is the name/label of view.

views: { 'main@': 'settings.tpl' }

This design will make sure your header and footer controllers are not executed on every state change.

Upvotes: 3

Related Questions