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 是一个JavaScript 框架。它可通过 注:建议把脚本放在 元素的底部。这会提高网页加载速度,因...
angluarjs中页面初始化的时候会出现语法{{}}在页面中问题,也即是页面闪烁问题。出现这个的原因是:由于...
AngularJS 通过被称为指令的新属性来扩展 HTML。AngularJS 指令AngularJS 指令是扩展的 HTML 属性,带有...
AngularJS 使用表达式把数据绑定到 HTML。AngularJS 表达式AngularJS 表达式写在双大括号内:{{ expres...
ng-repeat 指令可以完美的显示表格。在表格中显示数据 {{ x.Name }} {{ x.Country }} 使用 CSS 样式为了...
$http是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。读取 JSON 文件下是存储在web服务器上...