问题描述
我有一个2048
,我用ajax调用填充了数周。
其中一些项目应为红色(在<select>
处设置类)。
我宁愿不使用reddays > 0
来输出选项,因为我只会遇到问题,设置/获取ng-repeat
并以编程方式选择一个项目。
相反,我想使用ng-options,因此我需要指定哪些ng-model
:s具有某个类。
在堆栈溢出页面Angular.js - adding a class to an option with ng-options上,似乎有一个过时的解决方案,但是它在<option>
上引入了一个名为<select>
的属性。
我尝试在https://jsfiddle.net/AndersBillLinden/ne0z9vwm/10/
中使用它但所有项目都变成黑色。
我真的想像您看到的那样使用整个星期对象作为模型。 我不能那样做吗?
html:
options-class="{foo:num>3}"
js:
<div ng-app="app" ng-controller="testController" style="height: 100%">
Week:
<select id="week" style="width: 60px"
ng-change="on_week_changed()"
ng-options="w as w.num for w in weeks"
options-class="{redweek: reddays>0}"
ng-model="week">
</select>
</div>
css:
$scope.weeks =
[
{num: 1,reddays: 3},{num: 2,reddays: 0},{num: 3,{num: 4,reddays: 1}
];
$scope.on_week_changed = function()
{
alert($scope.week.num);
};
}).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);
}
});
});
});
}
};
});
解决方法
我更改了我的js,使其不依赖于value属性的存在。
var angular_app = angular.module("app",["ng"]);
angular_app.controller("testController",function ($scope)
{
$scope.weeks =
[
{num: 1,reddays: 3},{num: 2,reddays: 0},{num: 3,{num: 4,reddays: 1}
];
$scope.week = $scope.weeks[3];
$scope.on_week_changed = function()
{
alert($scope.week.num);
};
}).directive('optionsClass',function ($parse) {
return {
require: 'select',link: function(scope,elem,attrs,ngSelect) {
var optionsSourceStr = attrs.ngOptions.split(' ').pop(),getOptionsClass = $parse(attrs.optionsClass);
scope.$watch(optionsSourceStr,function(items) {
var options = elem.find("option");
angular.forEach(items,function(item,index) {
var classes = getOptionsClass(item);
var option = options.eq(index);
angular.forEach(classes,function(add,className) {
if(add) {
angular.element(option).addClass(className);
}
});
});
});
}
};
});