loostro loostro - 6 months ago 22
AngularJS Question

How can I use AngularJS filter in ngClass?

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

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

Comments