Angularjs 如何在ngClass中使用动态值

Angularjs 如何在ngClass中使用动态值,angularjs,Angularjs,我试图应用一个与范围变量相同的类名 例如: 因此,item.name的值被添加到类中。但这似乎没什么作用。有什么建议吗 谢谢 编辑: 这实际上是在select中使用ng选项完成的。例如: 现在,我想应用一个值为c.code 我发现以下指令似乎有效,但不适用于值的插值: angular.module('directives.app').directive('optionsClass', ['$parse', function ($parse) { 'use strict'; retu

我试图应用一个与范围变量相同的类名

例如:

因此,
item.name
的值被添加到类中。但这似乎没什么作用。有什么建议吗

谢谢

编辑:

这实际上是在select中使用ng选项完成的。例如:

现在,我想应用一个值为
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" />


这也被记录在了。

我想你错过了这个概念

条件css类如下所示:

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

我不认为你想要:

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

您可能想使用:


迟做总比不做好

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


对<代码>'和
{{
用于类名。

Angularjs使用条件应用类:

<div ng-class="{true:'class1',false:'class2'}[condition]" >

我使用的是angular 1.5.5,这些解决方案都不适合我

可以同时使用数组和映射语法,尽管它仅在中显示


这在某些情况下很有用:

HTML:


嗯,好吧,我的问题还不够清楚。我实际上是用选择框中的
ng选项来做这件事的,我想使用select的值并将其应用到选项上。@dave它仍然是一样的,只是
c.code
而不是
项。name
似乎对原始问题没有任何作用这将是正确的答案:)当你的类名是范围定义的变量时,这是合适的。这适用于1个条件,但是如果你尝试添加
和另一个带值的条件,它就不再起作用了。而且,当条件更改时,这不会更新类名。我正在寻找这个。一个带条件,一个带变量名。谢谢,我知道了现在数组语法::-)这正是我需要的。很难找到正确的搜索词!谢谢。在angular 1.6.4中,当条件更改时,它似乎不会更新类名。此条件返回true或false值,
<div ng-class="[item.name, {'other-name' : item.condition}]">
<div ng-class="getCssClass()"></div>
$scope.getCssClass = function () {
    return { item.name: item.name };
};