Search code examples
javascriptangularjsng-class

Angular ngClass ghost class


I was making a simple toggle of classes with ngClass, using Material Design Icons (probably irrelevant). Here's an example:

<button ng-click="toggle = !toggle">
  <i class="mdi" ng-class="{'mdi-filter': toggle, 'mdi-filter-remove': !toggle}"></i>
</button>

And it didn't work for some reason, the 'mdi-filter-remove' class would get removed on !true evaluation. So, to test, I changed the class to 'mdi-filter-outline'. With that class it somehow works fine! I only changed the class, if I put the previous one back it stops working again. And the strangest thing is, on toggle, before switching to 'mdi-filter-outline' class the 'mdi-filter-remove' class flashes for a split second.

If I set a break-point for the toggle and start clicking 'step over next function call' I indeed see 'mdi-filter-remove' after a few clicks, right after the line 17286 in angular.js is executed:

fn(value, ((last === initWatchVal) ? value : last), current);

That class is not used ANYWHERE in the project, I searched whole project with atom, no matches! Where does it come from?

Please help!


Solution

  • Do you have ngAnimate in your project? If you do, then adding and removing classes with ng-class causes some special classes to be added and removed behind the scenes, for use with transition animations. One of these special classes is a class with the -remove suffix. So for example, if you have a class called my-class that you are adding and removing with ng-class, then the classes my-class-add and my-class-remove will also show up alongside them whenever the element is transitioning. That's why you see it for a split second.

    So, you should just rename your class. The -remove suffix is clashing with what angular is doing automatically.