如何使用纳克级的选择与NG选项 [英] How to use ng-class in select with ng-options
问题描述
我有Person对象的数组
I have an array of Person objects
var persons = [
{Name:'John',Eligible:true},
{Name:'Mark',Eligible:true},
{Name:'Sam',Eligible:false},
{Name:'Edward',Eligible:false},
{Name:'Michael',Eligible:true}
];
和我使用的选择,像这样NG选项:
and i am using select with ng-options like this:
<select ng-model="Blah" ng-options="person.Name for person in persons"></select>
我要显示与符合条件的记录:假在红色的颜色。
所以,问题是我如何使用纳克级
在选择
序来实现这一目标?因为我们没有使用任何选项
标记它不会工作,如果我只需添加纳克级
在选择
元素本身。
I want to show the record with Eligible:false in red color.
So the problem is how do i use the ng-class
in select
inorder to achieve this? Since we are not using any option
tag it wont work if i simply add ng-class
in the select
element itself.
推荐答案
您可以创建一个处理的选项ngOptions指令处理,与适当的类更新后,这些指令。
You could create a directive that processed the options after the ngOptions directive is processed that updated them with the appropriate classes.
更新:旧code有一些错误,我已经学到了一点,因为我回答了这个问题。 下面是在1.2.2重做(但应在1.0.X工作以及)
Update: The old code had a few bugs, and I've learned a bit since I answered this question. Here is a Plunk that was redone in 1.2.2 (but should work in 1.0.X as well)
下面是更新的的code:
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);
}
});
});
});
}
};
});
下面是你在你的标记使用它:
Here's how you'd use it in your markup:
<select ng-model="foo" ng-options="x.name for x in items"
options-class="{ 'is-eligible' : eligible, 'not-eligible': !eligible }"></select>
它的工作原理就像纳克级呢,不同之处在于它是在每个单品中最收集基础。
It works like ng-class does, with the exception that it's on a per-item-in-the-collection basis.
这篇关于如何使用纳克级的选择与NG选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!