【发布时间】:2019-02-11 10:38:36
【问题描述】:
我无法更改选项类属性。 OptionClass 确实有效。我是从这个网站创建的。但是我的真实代码不起作用。不知道bug在哪里。
我只想通过表达式更改选项背景颜色,例如如果 id>100 则背景颜色为红色等。
我的选择
<select ng-model="firstSection" ng-options="o.label for o in options" multiple
class="invoiceSelect" options-class="{ 'is-eligible' : Id<100, 'not-eligible': !Id<100 }"></select>
我的填充方法
var myApp = angular.module('app', []);
myApp.controller('myCtrl', function ($scope, $http, $filter) {
$scope.getInvoiceByRfiPolicyId = function (rfiPolicyId) {
$http.get('http://somesitelink.com/' + rfiPolicyId)
.then(function (response) {
$scope.options = response.data.map(o=> {
return { label: 'Numbers:' + o.InvoiceNumber + ' InvDate:' + $scope.dateParse(o.InvoiceDate), value: o.InvoiceId, Id:o.InvoiceId, eligible: true }
});
});
}
});
这是我的 optionClass 函数
myApp.directive('optionsClass', function ($parse) {
return {
require: 'select',
link: function (scope, elem, attrs, ngSelect) {
var parts = attrs.ngOptions.split(' ');
var optionsSourceStr = parts[parts.indexOf('in') + 1];
var getOptionsClass = $parse(attrs.optionsClass);
scope.$watchCollection(optionsSourceStr, function (items) {
scope.$$postDigest(function () {
angular.forEach(items, function (item, index) {
var classes = getOptionsClass(item),
option = elem.find('option[value="' + item.id + '"]');
angular.forEach(classes, function (add, className) {
if (add) {
angular.element(option).addClass(className);
}
});
});
});
});
}
};
});
【问题讨论】:
-
你试过使用 ng-class 指令吗?这是以角度docs.angularjs.org/api/ng/directive/ngClass 操作类的方法
-
不适合用。因为我想改变一些有价值的选项。所以我没有任何选项元素。我正在使用 ng-options 属性。如果你是这方面的一个例子,我会调查它。
-
尝试使用 jQuery 添加类,应该可以。
-
你为什么不像这样使用
option标签和ng-repeat并删除ng-options?<option ng-repeat="o in options" value="{{o.value}}" ng-class="{red: o.value<3, green: o.value>2}">{{o.label}}</option> -
因为我的价值不是一个简单的数据。这是一个类,我使用它的不同属性。所以
标签: angularjs