angularjs – Controller is executed every time I change route

Question:

In index.html I have 2 views:

  • sidebar-left : where the menu is loaded after login.
  • content : where the page in question is loaded

I'm using angular-ui-router and after login the user is redirected to the dashboard.

The sidebar-left is loaded on the dashboard:

.state('dashboard', {
            url: "/dashboard",               
            views: {
                'content': {
                    templateUrl: 'view/dashboard.html',
                    resolve: {
                        auth : function ($q, Session) {
                            var userInfo = Session.getUserInfo();
                            if (userInfo) return $q.when(userInfo);
                            else return $q.reject({ authenticated: false });
                        }
                    },
                    controller: 'dashboard'
                },
                'sidebar-left' : { templateUrl: 'view/sidebar-left.html', controller: 'menu' }
            },
        })

It turns out that the sidebar-left is common on all pages, when moving from the dashboard to another area the sidebar disappears.

This I solved by adding the "sidebar-left" view to all routes.

It turns out that the "sidebar-left" view is associated with a controller that does a GET to the server and PHP reads the database and returns the menu.

Every time I change the route, this controller is executed doing an unnecessary GET to the server.

The problem is the logic used, how do I make the menu to be loaded only once?

Answer:

Actually the way it was implemented every time the 'dashboard' state is triggered the two controllers will be created again.

If your idea is to leave the 'sidebar-left' always present, you can use the state hierarchy content of the ui-router, see the following page: https://github.com/angular-ui/ui-router/ wiki/Nested-States-%26-Nested-Views

Specifically in your case, something like this:

state('root', {
   abstract: true,
   templateUrl: 'view/sidebar-left.html',
   controller: 'menu'
}).state('dashboard', {
   url: "/dashboard",
   parent: 'root',
   views: {
      'content': {
         templateUrl: 'view/dashboard.html',
         resolve: {
            auth: function ($q, Session) {
               var userInfo = Session.getUserInfo();
               if (userInfo) return $q.when(userInfo);
               else return $q.reject({ authenticated: false });
            }
         },
         controller: 'dashboard'
      }
   },
})
Scroll to Top