3 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以在處理ngOptions指令后創(chuàng)建一個(gè)處理選項(xiàng)的指令,以適當(dāng)?shù)念惛滤鼈儭?/p>
更新:舊代碼有一些錯(cuò)誤,自從我回答了這個(gè)問題以來,我學(xué)到了一些東西。這是在1.2.2中重做的Plunk(但也應(yīng)在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);
}
});
});
});
}
};
});
這是在標(biāo)記中使用它的方式:
<select ng-model="foo" ng-options="x.name for x in items"
options-class="{ 'is-eligible' : eligible, 'not-eligible': !eligible }"></select>
它像ng-class一樣工作,不同之處在于它是基于集合中的每個(gè)項(xiàng)目。
- 3 回答
- 0 關(guān)注
- 733 瀏覽
添加回答
舉報(bào)