Edgaras Karka
Edgaras Karka

Reputation: 7852

Angular onEnter ui.router method not work how expect

I have an Angular app and its ui.router module have an onEnter method. I want to call function when state menu item is clicked and state is changed. But now my app is not working correctly. E.g. I go to app.com/what and console print all 5 lines when app is loaded, and after that nothing is printed after menu click is clicked. I read this here

There are also optional 'onEnter' and 'onExit' callbacks that get called when a state becomes active and inactive respectively.

my console when page loaded:

[debug] changeMenu item_id:1495
[debug] changeMenu item_id:1342
[debug] changeMenu item_id:1344
[debug] changeMenu item_id:1346
[debug] changeMenu item_id:1346

My goal is call changeMenu function only when menu item is clicked or on init step.

          var changeMenu = function(itemID){
              console.log("[debug] changeMenu item_id:"+itemID);
              // for menu css
              $("#nav_menu li.active").removeClass("active");
              $("#nav_menu li#menu-item-"+itemID).addClass('active');
              $('#nav_menu').spasticNav();
          }
          //
          // Now set up the states
          $stateProvider
            .state('index', {
              url: "/",
              templateUrl: "main.html",
              onEnter: changeMenu(1495)
            })
            .state('what', {
              url: "/what",
              templateUrl: "what.html",
              onEnter: changeMenu(1342)
            })
            .state('where', {
              url: "/where",
              templateUrl: "where.html",
              onEnter: changeMenu(1344)

            })
            .state('cost_rent', {
              url: "/cost_rent",
              templateUrl: "cost_rent.html",
              onEnter: changeMenu(1346)

            })
            .state('cost_sell', { 
              url: "/cost_sell",
              templateUrl: "cost_sell.html",
              onEnter: changeMenu(1346)
            })
        });

Upvotes: 0

Views: 58

Answers (1)

Zhiliang Xing
Zhiliang Xing

Reputation: 1057

when you use onEnter, it expects a closure(callback function).onEnter: changeMenu(1495) is not a callback function, it execute the function, which is why all 5 debug messages show altogether. so what you can do is something like this:

$stateProvider
  .state('index', {
    url: "/",
    templateUrl: "main.html",
    onEnter: function() {
      changeMenu(1495);
    }
  })

Upvotes: 2

Related Questions