Search code examples
javascriptangularjsangularjs-scopeangularjs-ng-showsatellizer

$scope not updating on change


I'm using Satellizer for authentication, after I login, the login/register button in the header should change to logout but they don't.

Here is my header directive:

angular.module('pages.components.navHeader', [
    'common.services.authenticationService'
])

    .directive('navHeader', function () {
                   var directive = {};

                   directive.restrict = "E";
                   directive.templateUrl = "navHeader.tpl.html";
                   directive.controller = ['$scope','$location', 'CONFIG', 'authenticationService', function navHeaderCtrl($scope, $location, CONFIG, authenticationService) {
                       $scope.isAuthenticated = authenticationService.isAuthenticated();

                       $scope.logout = function (){
                           authenticationService.logout();
                       };
                   }];

                   return directive;
               });

Here is the interesting part of my header template:

<li ng-show="!isAuthenticated"><a ng-href="#">Login</a></li>
<li ng-show="!isAuthenticated"><a ng-href="#">Register</a></li>
<li ng-show="isAuthenticated"><a ng-click="logout()" href="#">Logout</a></li>

I have a factory as an extra layer in case satellizer doesn't work for me, which is just a directive that does this:

   .factory ('authenticationService', ['CONFIG', '$auth', function authenticationService (CONFIG, $auth) {
    var authentication = {};

    authentication.isAuthenticated = function (){
        return $auth.isAuthenticated();
    };
    return authentication;
}])

So even when I click logout, the header doesn't update. Am I doing something wrong on how I set the isAuthenticated in my header?


Solution

  • Change your controller code to this

    $scope.isAuthenticated = authenticationService.isAuthenticated;
    

    And then on html you could simply use.

    ng-show="isAuthenticated()"
    

    Note

    ng-show will call authenticationService.isAuthenticated method on each digest cycle