ng-class with function and Expression

Vivek Panday picture Vivek Panday · May 29, 2015 · Viewed 19k times · Source

I need to add two classes by using ng-class ,one class I am getting by a function another I need to get by an expression - Below is code which I am using but getting some syntax error -

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

What would be correct syntax if it is possible to use function and expression together.

Answer

Pankaj Parkar picture Pankaj Parkar · May 29, 2015

You had wrong ng-class syntax, it should be in JSON format like ng-class="{'used': expression2 }", expression will return Boolean on basis of that class will get added or removed from the class attribute value.

As your getFieldClass method is returning class name then you could shift your both class logic in 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};
}