0

I want my ng-class to update when the variable in my controller changes. For some reason, it is only triggered on the page load and whilst the variable change, the ng-class does not update to reflect this.

Here is the code that triggers the variable change:

<a class="cs-mobile-menu__close-icon" ng-click="switchMobileMenu('right')">
</a>

Here is the code which I want to change depending on the variable:

<div class="right-menu__user"
        ng-class="{
                  'animate': true,
                  'animate--leave': !isRightMenuOpen}">
  {{user.firstName}} {{user.lastName}}
</div>

Here is the corresponding code from the controller:

$rootScope.isLeftMenuOpen = false;
$rootScope.isRightMenuOpen = false;

$scope.switchMobileMenu = function(direction) {
       if (direction === 'left') {
           $scope.isLeftMenuOpen = !($scope.isLeftMenuOpen);
       } else {
           $scope.isRightMenuOpen = !($scope.isRightMenuOpen);
       }
};

It seems that ng-class is only set on the initial ng-click. I believe I need to wrap the above function in a $scope.apply() function so that the ng-class watches for changes and applies them as the ng-click toggles the variable. Am I on the right track? If so, how would I do this?

1
  • does it work if you replace $rootScope with $scope? Commented Nov 13, 2016 at 17:09

1 Answer 1

1

You don't need $scope.$apply. Working example: https://jsbin.com/fogasiniku/edit?html,js,output

Do you really have double dashes in the CSS class name?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.