I_D*_*ing 37 select angularjs 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}
];
Run Code Online (Sandbox Code Playgroud)
我正在使用选择这样的ng-options:
<select ng-model="Blah" ng-options="person.Name for person in persons"></select>
Run Code Online (Sandbox Code Playgroud)
我想显示与记录符合条件的:假的红颜色.所以问题是如何使用ng-class
in select
来实现这一目标?因为我们没有使用任何option
标签,如果我只需添加它不会工作ng-class
在select
元素本身.
Ben*_*esh 35
您可以创建一个指令,在处理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);
}
});
});
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
以下是您在标记中使用它的方法:
<select ng-model="foo" ng-options="x.name for x in items"
options-class="{ 'is-eligible' : eligible, 'not-eligible': !eligible }"></select>
Run Code Online (Sandbox Code Playgroud)
它的工作方式与ng-class类似,但除了它是基于每个项目的集合.
Ste*_*wie 13
在这种情况下,只有在使用ng-repeat
选项标记时才能应用ng-class :
<select ng-model="Blah">
<option ng-repeat="person in persons" ng-class="{red: person.Eligible}">{{person.Name}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)
这将为您的"合格"人员提供自定义课程,但CSS不会在不同的情况下保持一致.