Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a dynamic value with ngClass

Tags:

angularjs

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);             }           });         });       });     }   };  }]); 
like image 416
dzm Avatar asked Jul 03 '14 20:07

dzm


People also ask

Can we use NgStyle and ngClass together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

How do you use ngClass directive?

AngularJS ng-class DirectiveIf it is a string, it should contain one or more, space-separated class names. As an object, it should contain key-value pairs, where the key is the class name of the class you want to add, and the value is a boolean value. The class will only be added if the value is set to true.


1 Answers

Better later than never.

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

yes. ' and {{ for classname.

like image 119
knes Avatar answered Oct 01 '22 03:10

knes