如何在带有ng-options的select中使用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}

];

我正在使用带有ng-options这样的select:


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

我想显示与记录符合条件的:假的红颜色。所以问题是我如何使用ng-class在select序来实现这一目标?因为我们没有使用任何option标签,如果我只需添加它不会工作ng-class在select元素本身。


小怪兽爱吃肉
浏览 644回答 3
3回答

qq_笑_17

您可以在处理ngOptions指令后创建一个处理选项的指令,以适当的类更新它们。更新:旧代码有一些错误,自从我回答了这个问题以来,我学到了一些东西。这是在1.2.2中重做的Plunk(但也应在1.0.X中工作)这里更新了代码:app.directive('optionsClass', function ($parse) {&nbsp; return {&nbsp; &nbsp; require: 'select',&nbsp; &nbsp; link: function(scope, elem, attrs, ngSelect) {&nbsp; &nbsp; &nbsp; // get the source for the items array that populates the select.&nbsp; &nbsp; &nbsp; var optionsSourceStr = attrs.ngOptions.split(' ').pop(),&nbsp; &nbsp; &nbsp; // use $parse to get a function from the options-class attribute&nbsp; &nbsp; &nbsp; // that you can use to evaluate later.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; getOptionsClass = $parse(attrs.optionsClass);&nbsp; &nbsp; &nbsp; scope.$watch(optionsSourceStr, function(items) {&nbsp; &nbsp; &nbsp; &nbsp; // when the options source changes loop through its items.&nbsp; &nbsp; &nbsp; &nbsp; angular.forEach(items, function(item, index) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // evaluate against the item to get a mapping object for&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // for your classes.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var classes = getOptionsClass(item),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // also get the option you're going to need. This can be found&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // by looking for the option with the appropriate index in the&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // value attribute.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; option = elem.find('option[value=' + index + ']');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // now loop through the key/value pairs in the mapping object&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // and apply the classes that evaluated to be truthy.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; angular.forEach(classes, function(add, className) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(add) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; angular.element(option).addClass(className);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; };});这是在标记中使用它的方式:<select ng-model="foo" ng-options="x.name for x in items"&nbsp;&nbsp; &nbsp;options-class="{ 'is-eligible' : eligible, 'not-eligible': !eligible }"></select>它像ng-class一样工作,不同之处在于它是基于集合中的每个项目。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS