select - 如何在带有 ng-options 的 select 中使用 ng-class

标签 select angularjs ng-class

我有一个 Person 对象数组

var persons = [
{Name:'John',Eligible:true},
{Name:'Mark',Eligible:true},
{Name:'Sam',Eligible:false},
{Name:'Edward',Eligible:false},
{Name:'Michael',Eligible:true}
];

我正在使用 select 和 ng-options,如下所示:

<select ng-model="Blah" ng-options="person.Name for person in persons"></select>

我想以红色颜色显示Eligible:false记录。 所以问题是我如何在 select 中使用 ng-class 来实现这一目标?由于我们没有使用任何 option 标签,如果我只是在 select 元素本身中添加 ng-class ,它就不起作用。

最佳答案

您可以创建一个指令,在处理 ngOptions 指令后处理选项,并使用适当的类更新它们。

更新:旧代码有一些错误,自从回答这个问题以来我学到了一些东西。 Here is a Plunk that was redone in 1.2.2 (but should work in 1.0.X as well)

以下是更新后的代码(2013 年 11 月 30 日 3:17):

app.directive('optionsClass', function ($parse) {
  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);
            }
          });
        });
      });
    }
  };
});

以下是在标记中使用它的方法:

<select ng-model="foo" ng-options="x.name for x in items" 
        options-class="{ 'is-eligible' : eligible, 'not-eligible': !eligible }">
</select>

它的工作方式类似于 ng-class,不同之处在于它是基于集合中的每个项目。

关于select - 如何在带有 ng-options 的 select 中使用 ng-class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15264051/

相关文章:

mysql - 如何根据最常见的字段更新值?

jquery同位素选择/选项和未排序列表

javascript - 选择标签的选定值不会在 angularjs 中的开关外部更改

javascript - 如何对 Controller 上的 AngularJS 服务中的数据变化使用react

javascript - 通过文件协议(protocol)访问 Angular 模板(即在本地主机上)

AngularJS 工厂在 ng-class 内的 body 标签不起作用

javascript - ngClass 不更新类

jquery 获取 select() 选择

sql - 搜索多个表的顺序

javascript - 如何使用 ngClass 做 if-else?