Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 657
ioleo Avatar asked Dec 30 '13 11:12

ioleo


People also ask

What is the correct way to apply filter in AngularJS?

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.

How does filter work in AngularJS?

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.

What is ngClass in AngularJS?

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.

Can we use filter in NG model?

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


2 Answers

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

like image 171
Khanh TO Avatar answered Oct 07 '22 06:10

Khanh TO


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.

like image 31
Jason Avatar answered Oct 07 '22 06:10

Jason