angularjs – 如何使用ngClass的动态值

前端之家收集整理的这篇文章主要介绍了angularjs – 如何使用ngClass的动态值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图应用与一个作用域变量相同的类名.

例如:

< divng-class =“{item.name:item.name}”>

所以item.name的值被添加到类中.这似乎什么都不做.有什么建议如何做到这一点?

谢谢!

编辑:

这实际上是在选择中使用ng选项来完成的.例如:

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

现在,我想应用一个具有c.code值的类名

我发现以下指令,似乎有效,但不是插值的值:

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);
            }
          });
        });
      });
    }
  };

}]);
比以往更好.
<div ng-class="{'{{item.name}}' : item.condition}">

是. ‘和{{for classname.

猜你在找的Angularjs相关文章