Search code examples
javascripthtmlangularjsng-class

Angular ngClass is not updating my classes even though my condition change as expected


I have something like this in a template I am creating

<div ui-view id="app" class="nng-3" ng-class="{ 'app-mobile': app.isMobile, 'app-navbar-fixed': app.layout.isNavbarFixed, 'app-sidebar-fixed': app.layout.isSidebarFixed, 'app-sidebar-closed': app.layout.isSidebarClosed, 'app-footer-fixed': app.layout.isFooterFixed }"></div>

The values app.layout.isNavbarFixed, etc are initialized with either zero or one, and for the first time the page loads the appropriate classes are inserted into my div. Any change after that though, by means of a button that sets those values, is not reflected on my class attributes by ng-class.

If I directly print those variables in my template, eg. {{app.layout.isSidebarFixed}} I can see them changing from true to false and vice versa, but ng-class will not update or remove any new classes.

I am not sure where to begin and look for the solution for this since with my limited knowledge I cant spot any obvious mistake immediately. Does anyone have any idea on what causes this issue?


Solution

  • A workaround of mine is to manipulate a model variable just for the ng-class toggling:

    1) Whenever my list is empty, I update my model:

    $scope.extract = function(removeItemId) {
        $scope.list= jQuery.grep($scope.list, function(item){return item.id != removeItemId});
        if (!$scope.list.length) {
            $scope.liststate = "empty";
        }
    }
    

    2) Whenever my list is not empty, I set another state

    $scope.extract = function(item) {
        $scope.list.push(item);
        $scope.liststate = "notempty";
    }
    

    3) I use this additional model on my ng-class:

    ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty'}"
    

    Update*: Also you can add any other states if needed and use at ng-class like:

    ng-class="{'bg-empty': liststate == 'empty', 'bg-notempty': liststate == 'notempty', 'bg-additional-state', liststate == 'additional-state'}"
    

    Because you know, an initially empty list state is not equal with a list which is emptied by command.