3 回答
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一样工作,不同之处在于它是基于集合中的每个项目。
- 3 回答
- 0 关注
- 695 浏览
添加回答
举报