Alexandr  Kovalenko
Alexandr Kovalenko

Reputation: 51

Angularjs ngClass work not correct or how he work?

Why ng-class don't work with scope var's

sheikContolls.controller('MainPageController', ['$scope', 'authService',
    function ($scope, authService) {
       if(!authService.isAuthenticated()){
            $scope.class1 = "good";
       }
       else {
            $scope.class1= "bad";
       }
    }
    ]);

HTML:

<div class="demo" ng-class="class1"></div>

When you first start the class is added and we have class="demo good", but if then isAuthenticated() return true, class don't change, why ?? The same with next HTML:

<div class="demo {{class1}}"></div>

If i make a function - all work perfect.

<div class="demo" ng-class="getClass()"></div>

Upvotes: 0

Views: 222

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191809

authService.isAuthenticated is not bound to the scope, and the controller definition function only runs once so initially class1 is good, but that functionality never runs again.

You will have to bind isAuthenticated to the scope in some way for this to work. I might consider an alternate solution like binding to a value on authService that is updated after authorization is done, but in the meantime you can do this:

$scope.getClass = function () {
    if (authService.isAuthenticated()) {
        return "bad";
    }
    return "good";
};

http://plnkr.co/edit/1xFRoTusNLHXeIhosGOp?p=preview

Upvotes: 1

hoeni
hoeni

Reputation: 3300

The code in the controller is called only once when the controller is instantiated and never again later, so it does never check authService.isAuthenticated() again.

When you use a function in your HTML-Code that function is called regularely and watched for its result, so later changes will be applied.

You could move the detailed check in the controller and call it from the HTML for some encapsulation:

sheikContolls.controller('MainPageController', ['$scope', 'authService',
   function ($scope, authService) {
       $scope.isAuthenticated = function(){
           return authService.isAuthenticated();
       };
   }
]);

<div class="demo" ng-class="{good: isAuthenticated(), bad: !isAuthenticated() }"></div>

Upvotes: 1

Related Questions