2014-10-16 25 views
1

有人問了一個類似的問題(How to use ng-class in select with ng-options),但我也添加了它,因爲它與其他人的問題的答案有關。Angular.js - 使用ng-options爲選項添加一個類

的解決方案是真棒,但我不太明白。

答案是創造一個指令 - http://plnkr.co/edit/rbc4GWBffi4eFYhbvS6u?p=preview

我想要做同樣的事情,但添加的類應該與items.name相同。我怎麼做?

console.clear(); 
 

 
var app = angular.module('angularjs-starter', []); 
 

 
app.controller('MainCtrl', function($scope) { 
 
    $scope.items = [ 
 
    { name: 'foo', id: 1, eligible: true }, 
 
    { name: 'bar', id: 2, eligible: false }, 
 
    { name: 'test', id: 3, eligible: true } 
 
    ]; 
 
}); 
 

 
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); 
 
      } 
 
      }); 
 
     }); 
 
     }); 
 
    } 
 
    }; 
 
});
/* CSS goes here */ 
 
.is-eligible { 
 
    color: green; 
 
} 
 
.not-eligible { 
 
    color: red; 
 
}
<!DOCTYPE html> 
 
<html ng-app="angularjs-starter"> 
 
    
 
    <head lang="en"> 
 
    <meta charset="utf-8"> 
 
    <title>Custom Plunker</title> 
 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.min.js"></script> 
 
    <link rel="stylesheet" href="style.css"> 
 
    <script> 
 
     document.write('<base href="' + document.location + '" />'); 
 
    </script> 
 
    <script src="app.js"></script> 
 
    </head> 
 
    
 
    <body ng-controller="MainCtrl"> 
 
    <select ng-model="foo" ng-options="x.name for x in items" 
 
      options-class="{ 'is-eligible' : eligible, 'not-eligible': !eligible }"></select> 
 
    </body> 
 

 
</html>

預先感謝

+1

如果您使用select with ng-repeat,那麼它會很容易做 – harishr 2014-10-16 16:25:01

+0

對我而言不適用於osx和angular 1.2.26上的chrome – mirage 2016-09-15 09:40:58

回答

相關問題