ng-switch is not working as expected

306 views Asked by At

Maybe the use of the 2-ways binding and $watch is still not very clear to me.. but I was expecting that this piece of code should work!

I have a topNavbar directive in my index.html page. The topNavbar should show the loginButton if the user is not logged, otherwise a loggedinButton if he is already logged.

So I have a ng-switch in the topNavbar, looking at the isLogged attribute of the CurrentUserService. I guess this is something like $watch(CurrentUserService.isLogged).

However, when I change CurrentUserService.isLogged to true, the ng-switch is not immediately updated. It gets updated after any my action, like clicking on a button o changing the view. Why it's not working as I expect?

This is my code:

index.html

<html lang="it" xmlns:ng="http://angularjs.org" ng-app="epoiApp">
  ...
  <body style="overflow-y: auto;">
    ...
    <top-navbar></top-navbar>
    ...
  </body>
</html>

directive template topNavbar

<div ng-switch on="navbarCtrl.isLogged()">
  <div ng-switch-when="false">
    <login-button></login-button>
  </div>
  <div ng-switch-when="true">
    <loggedin-button></loggedin-button>
  </div>                                            
</div>

controller navbarCtrl

controller:function(CurrentUserService)
            {
             this.isLogged = function()
                            {return CurrentUserService.isLogged();} 
            }

CurrentUserService

.service('CurrentUserService', function () 
  {   
   // initialization
   _islogged = false;

   this.isLogged = function() 
        { return _islogged; };

  }  

thank you

1

There are 1 answers

0
Dan On BEST ANSWER

Here is a plunker.

Angular kicks off a digest cycle when there is a change to the model (which is why after you interacted with the UI in some way you noticed it update).

A change in a closure variable inside a service is not part of the model, so you need to manually $scope.$apply() to start a digest cycle when you know this variable has been updated.