一尘不染

如何在ngClass中使用动态值

angularjs

我试图应用与作用域变量相同的类名。

例如:

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

以便将的值item.name添加到类中。不过,这似乎没有任何作用。有关如何执行此操作的任何建议?

谢谢!

编辑:

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

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

}]);

阅读 276

收藏
2020-07-04

共1个答案

一尘不染

我使用的是角度1.5.5,但这些解决方案都不适合我。

尽管仅在这里的最后一个示例中显示,但可以一次使用数组和映射语法

<div ng-class="[item.name, {'other-name' : item.condition}]">
2020-07-04