35

I'm trying to apply a class name that's the same as a scope variable.

For example:

<div ng-class="{item.name : item.name}">

So that the value of item.name is added to the class. This doesn't seem to do anything though. Any suggestions on how to do this?

Thanks!

EDIT:

This is actually being done within a select, using ng-options. For example:

<select ng-options="c.code as c.name for c in countries"></select>

Now, I want to apply a class name that has the value of c.code

I found the following directive, which seems to work, but not with interpolation of the value:

angular.module('directives.app').directive('optionsClass', ['$parse', function ($parse) {
  'use strict';

  return {
    require: 'select',
    link: function(scope, elem, attrs, ngSelect) {
      // get the source for the items array that populates the select.
      var optionsSourceStr = attrs.ngOptions.split(' ').pop(),
      // use $parse to get a function from the options-class attribute
      // that you can use to evaluate later.
          getOptionsClass = $parse(attrs.optionsClass);

      scope.$watch(optionsSourceStr, function(items) {
        // when the options source changes loop through its items.
        angular.forEach(items, function(item, index) {
          // evaluate against the item to get a mapping object for
          // for your classes.
          var classes = getOptionsClass(item),
          // also get the option you're going to need. This can be found
          // by looking for the option with the appropriate index in the
          // value attribute.
              option = elem.find('option[value=' + index + ']');

          // now loop through the key/value pairs in the mapping object
          // and apply the classes that evaluated to be truthy.
          angular.forEach(classes, function(add, className) {
            if(add) {
              angular.element(option).addClass(className);
            }
          });
        });
      });
    }
  };

}]);
0

6 Answers 6

74

Better later than never.

<div ng-class="{'{{item.name}}' : item.condition}">

yes. ' and {{ for classname.

4
  • That's the proper one for when your class names are scope-defined variables. Commented Jul 29, 2015 at 18:15
  • 7
    This works for 1 condition, but if you try to add , and another condition with value it doesn't work anymore. Commented Feb 24, 2017 at 9:08
  • 6
    Also this doesn't update the classname when the condition changes Commented Mar 13, 2017 at 14:18
  • 1
    @CristianMuscalu - This worked with multiple conditions when I added this logic at the end. Eg: "{'red':item.name='abc','{{item.name}}' : item.condition}" Commented Aug 24, 2021 at 13:31
50

I'm on angular 1.5.5 and none of these solutions worked for me.

It is possible to use the array and map syntax at once though it's only shown in the last example here

<div ng-class="[item.name, {'other-name' : item.condition}]">
3
  • I was looking for this. One with condition and one with variable name. Thanks I know now that array syntax. :-) Commented Jan 2, 2017 at 15:58
  • This was exactly what I needed. Really hard to find the right search terms for this! Thank you.
    – BigglesZX
    Commented Jan 24, 2017 at 15:04
  • 1
    on angular 1.6.4 it doesn't seems to update the classname when the condition changes
    – Dmitry
    Commented Nov 29, 2017 at 11:56
12

Simply using the variable should be sufficient:

<div ng-class="item.name" />

This is also documented in the official documentation.

4
  • Hm, ok my question was not clear enough. I'm actually doing this with ng-options in a select box and want to use the value of the select and apply it to the option.
    – dzm
    Commented Jul 3, 2014 at 20:51
  • @dave it is still the same, just c.code instead of item.name
    – dirkk
    Commented Jul 3, 2014 at 20:53
  • Doesn't seem to do anything
    – dzm
    Commented Jul 3, 2014 at 20:55
  • 1
    For the original question this would be the right answer :) Commented Sep 19, 2015 at 15:16
7

I think you missed the concept.

A conditional css class looks like this:

<div ng-class="{'<css_class_name>': <bool_condition>}">

And I dont think you want:

<div ng-class="{'true': true}">

You probally want to use:

<div ng-class="item.name"></div>

1

Angularjs Apply class with condition:

<div ng-class="{true:'class1',false:'class2'}[condition]" >
1
  • This condition return true or false value, <div ng-class="{true:'class1',false:'class2'}[statusId==1 ]" >
    – Rajeev
    Commented Jul 5, 2017 at 14:38
0

This can be useful in some cases:

HTML:

<div ng-class="getCssClass()"></div>

JS:

$scope.getCssClass = function () {
    return { item.name: item.name };
};
1
  • that's the best solution if you need more logic for css classes
    – OzzyCzech
    Commented Aug 21, 2021 at 7:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.