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).
In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for the filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.
The “filter” Filter in AngularJS is used to filter the array and object elements and return the filtered items. In other words, this filter selects a subset (a smaller array containing elements that meet the filter criteria) of an array from the original array.
The ng-class Directive in AngularJS is used to specify the CSS classes on HTML elements. It is used to dynamically bind classes on an HTML element. The value for the ng-class has either string, an object, or an array. It must contain more than one class name, which is separated by space, in the case of a string.
You can't use a filter in ng-model as it needs the expression to be assignable (i.e. it must be able to appear on the left hand side of an assignment).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With