Ng class with function and expression

I need to add two classes using ng-class, one class that I get from the function I need to get from the expression - Below is the code that I use, but I get a syntax error -

<div class="field-icon" ng-class="getFieldClass(entry.entry_type_id) , 'used': entry_map[entry.guid] > 0" ></div> 

What will be the correct syntax if you can use a function and an expression together.

+6
source share
3 answers

You did not have the correct ng-class syntax, it must be in JSON format, for example ng-class="{'used': expression2 }" , the expression will return a Boolean based on this class, which will be added or removed from the value of the attribute class.

As your getFieldClass method returns the class name, then you can transfer your class logic to the getFieldClass method

Markup

 <div class="field-icon" ng-class="getFieldClass(entry)" ></div> 

code

 $scope.getFieldClass = function(entry){ //use entry.entry_type_id here to decide class which is first //'text-box-icon' class has been selected on some condition based on entry.entry_type_id return {"text-box-icon": true, 'used': $scope.entry_map[entry.guid] > 0}; } 
+3
source

You can write both a function and an expression in an array.

Example:

  <div class="field-icon" ng-class="[getFieldClass(entry.entry_type_id), {'used':entry_map[entry.guid] > 0}]"></div> 

Live example here: https://plnkr.co/edit/OWfkAwJiombrehiS7p9o?p=preview

+3
source

You should do something like this:

 <div class="field-icon" ng-class="getClasses(entry)"></div> 

where your method is as follows:

 $scope.getClasses = function(entry) { var classes = {}; if (entry_map[entry.guid] > 0) classes['used'] = true; if (various-logic) classes['custom-class-one'] = true; else if (various-logic) classes['custom-class-two'] = true; //etc return classes; } 
-1
source

Source: https://habr.com/ru/post/988167/


All Articles