如何在ngClass中使用动态值 [英] How to use a dynamic value with ngClass
问题描述
我正在尝试应用与范围变量相同的类名.
I'm trying to apply a class name that's the same as a scope variable.
例如:
<div ng-class="{item.name : item.name}">
以便将item.name
的值添加到类中.不过,这似乎没有任何作用.有关如何执行此操作的任何建议?
So that the value of item.name
is added to the class. This doesn't seem to do anything though. Any suggestions on how to do this?
谢谢!
这实际上是在选择中使用ng-options完成的.例如:
This is actually being done within a select, using ng-options. For example:
<select ng-options="c.code as c.name for c in countries"></select>
现在,我想应用一个值为c.code
Now, I want to apply a class name that has the value of c.code
我找到了以下指令,该指令似乎可行,但不能对该值进行插值:
I found the following directive, which seems to work, but not with interpolation of the value:
angular.module('directives.app').directive('optionsClass', ['$parse', function ($parse) {
'use strict';
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);
}
});
});
});
}
};
}]);
推荐答案
我使用的是角度1.5.5,但这些解决方案都不适合我.
I'm on angular 1.5.5 and none of these solutions worked for me.
尽管仅在 the最后一个例子在这里
<div ng-class="[item.name, {'other-name' : item.condition}]">
这篇关于如何在ngClass中使用动态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!