How can I use AngularJS filter in ngClass?

ioleo picture ioleo · Dec 30, 2013 · Viewed 14.9k times · Source

I'm curretly learning AngularJS and playing with the tutorial.

I'm modifying the tutorial example filter to return some string:

angular.module('phonecatFilters', []).filter('checkmark', function() {
  return function(input) {
    return input ? 'true-class' : 'false-class';
  };
});

And I'd like to use that in ngClass as follows:

{{phone.trueVal  | checkmark}} <i ng-class="{{phone.trueVal  | checkmark }}"></i>
{{phone.falseVal | checkmark}} <i ng-class="{{phone.falseVal | checkmark }}"></i>

The results to:

true-class <i class="false-class">
false-class <i class="false-class">

Now.. while for simple view the filter works as expected.. why does it not work for ngClass? What whould be the correct way to use a filtered value in ngClass (and other like ngSrc etc).

Answer

Khanh TO picture Khanh TO · Dec 30, 2013

In your case, you should use class instead of ng-class because you render the class name directly on the html without evaluation.

<div ng-controller="MyCtrl">
   <i class="{{phone.trueVal  | checkmark }}">{{phone.trueVal  | checkmark}}</i>
   <i class="{{phone.falseVal | checkmark }}">{{phone.falseVal | checkmark}}</i>
</div>

DEMO