Search code examples
angularjsternary-operatorng-class

ng-class dynamic doesn't change when resize window


I tried the ng-class directive with a ternary and it works very well when the page load. My reference is the widthWindow.xs variable, it is "true" when the window size is a mobile, but there is a resize put it to "false" but the class does not change, the ng-class not dynamically changes. Why?

in the controller:

$scope.myResize = funcion(){
   var number = $window.innerWidth;
   if (number > 767) {
      $scope.widthWindow.xs = false;
   }else{
      $scope.widthWindow.xs = true;
   }
};

in the html:

<p ng-class="widthWindow.xs ? 'borderVoteNewsTop' : 'borderVoteNewsLeft'">Don't change when there is a resize</p>

Solution

  • Since the 'resize' event comes form outside the Angular framework, you need to integrate its actions with the AngularJS digest cycle. Use $apply.

    $scope.myResize = function(){
       var number = $window.innerWidth;
       if (number > 767) {
          $scope.$apply("widthWindow.xs = false");
       }else{
          $scope.$apply("widthWindow.xs = true");
       }
    };
    

    After the $apply executes the Angular expression, it will automatically invoke a digest cycle and the watcher in the ng-class directive will see the change and update the class.