Home Ask Login Register

Developers Planet

Your answer is one click away!

Toni Mora February 2016

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;
      $scope.widthWindow.xs = true;

in the html:

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


georgeawg February 2016

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");
      $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.

Rémi Becheras February 2016

Your syntax for the ngClass directive is not correct.

Use it as following:

  ng-class="{'borderVoteNewsTop': widthWindow.xs, 'borderVoteNewsLeft': !widthWindow.xs}"
  Change when there is a resize

Check out the directive documentation: https://docs.angularjs.org/api/ng/directive/ngClass

Post Status

Asked in February 2016
Viewed 1,395 times
Voted 9
Answered 2 times


Leave an answer

Quote of the day: live life