亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在帶有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 關注
  • 726 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號