我有一个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-classin select才能实现此目的?因为我们没有使用任何option标签,如果我只需添加它不会工作ng-class在select元素本身。
ng-class
select
option
您可以在处理ngOptions指令后创建一个处理选项的指令,以适当的类更新它们。
更新 :旧代码有一些错误,并且自回答这个问题以来,我学到了一点。这是在1.2.2中重做的Plunk(但也应在1.0.X中工作)
此处 更新 了代码 (13年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一样工作,不同之处在于它是基于集合中的每个项目。