为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

小怪兽爱吃肉 2019-11-02 09:56:42
我有一个Person对象数组var persons = [{Name:'John',Eligible:true},{Name:'Mark',Eligible:true},{Name:'Sam',Eligible:false},{Name:'Edward',Eligible:false},{Name:'Michael',Eligible:true}];我正在使用带有ng-options这样的select:<select ng-model="Blah" ng-options="person.Name for person in persons"></select>我想显示与记录符合条件的:假的红颜色。所以问题是我如何使用ng-class在select序来实现这一目标?因为我们没有使用任何option标签,如果我只需添加它不会工作ng-class在select元素本身。
查看完整描述

3 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

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


更新:旧代码有一些错误,自从我回答了这个问题以来,我学到了一些东西。这是在1.2.2中重做的Plunk(但也应在1.0.X中工作)


这里更新了代码:


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一样工作,不同之处在于它是基于集合中的每个项目。


查看完整回答
反对 回复 2019-11-02
  • 3 回答
  • 0 关注
  • 640 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信