19

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).

Andrew Sula
  • 939
  • 8
  • 24
ioleo
  • 4,697
  • 6
  • 48
  • 60
  • It works for me: http://jsfiddle.net/s3x2F/ – Oliver Dec 30 '13 at 11:57
  • 1
    @OlivérKovács css rules are not applied.. http://jsfiddle.net/ja3h8/1/ why? – ioleo Dec 30 '13 at 12:17
  • 1
    http://jsfiddle.net/Zmetser/ja3h8/3/ Skip the ng-class an use class with the filter, or do the declarative approach: http://jsfiddle.net/Zmetser/3L3de/1/ – Oliver Dec 30 '13 at 13:16

2 Answers2

24

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

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • i don't know why it does not work on AngularJS tutorial project.. but I see it working in your demo so I guess it must be some silly mistake on my end somewhere in the code... – ioleo Dec 30 '13 at 19:01
  • ngClass takes either an object or a string, so you can do ng-class=" 'myClass'+item.priority " https://stackoverflow.com/a/14644299/1702919 – Pierre Maoui Jun 07 '17 at 08:43
15

This worked for me. Just stared with AngularJS so I'm not sure if the functionality was added as part of an update since this question is a couple years old.

ng-class="{ 'has-error': (login.form | validField:'username') }"

After adding the parentheses, it worked.

Jason
  • 803
  • 9
  • 15