ng-class with function and Expression
Asked Answered
P

3

15

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.

Pharyngology answered 29/5, 2015 at 13:26 Comment(7)
you need to wrap it in curly braces ng-class="{getFieldClass(entry.entry_type_id) , 'used': entry_map[entry.guid] > 0}"Anamariaanamnesis
@tpie, I very much doubt that it'll work. This is not a valid JS object definitionInterplanetary
What's the return value of getFieldClass?Interplanetary
Is this a $scope function()???Adlai
@Anamariaanamnesis Its not working ..Pharyngology
it wasn't an answer, it was a comment. The syntax uses curly braces.Anamariaanamnesis
What's the return value of getFieldClass? retrun some custom css classPharyngology
A
15

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};
}
Aeromechanic answered 29/5, 2015 at 13:34 Comment(0)
A
9

You can write both function and expression in 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

Acrosstheboard answered 28/7, 2017 at 13:11 Comment(3)
I don't think your syntax is correct, need to wrap the expression in JSON, then put them in array. like: [getFieldClass(entry.entry_type_id), {'used':entry_map[entry.guid] > 0}]Antimasque
Yes. I missed. Thanks for pointing out. I also updated live exampleAcrosstheboard
Thanks for your sample with " [getFieldClass(entry.entry_type_id)] "Gemmell
D
-1

You should be able to do something like this:

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

where your method looks like:

$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;
}
Drouin answered 29/5, 2015 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.