我正在尝试应用与范围变量相同的类名.
例如:
<div ng-class="{item.name : item.name}">
这样就可以将值item.name添加到类中.但这似乎没有做任何事情.有关如何做到这一点的任何建议?
谢谢!
编辑:
这实际上是使用ng-options在select中完成的.例如:
<select ng-options="c.code as c.name for c in countries"></select>
现在,我想应用一个值为的类名 c.code
我找到了以下指令,它似乎有效,但没有插值:
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);
}
});
});
});
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
小智 68
比以后更好.
<div ng-class="{'{{item.name}}' : item.condition}">
Run Code Online (Sandbox Code Playgroud)
是.'和{{classname.
pha*_*zei 44
我的角度为1.5.5,这些解决方案都不适合我.
虽然它只在这里的最后一个例子中显示,但可以一次使用数组和映射语法
<div ng-class="[item.name, {'other-name' : item.condition}]">
Run Code Online (Sandbox Code Playgroud)
我想你错过了这个概念.
条件css类如下所示:
<div ng-class="{'<css_class_name>': <bool_condition>}">
Run Code Online (Sandbox Code Playgroud)
我不认为你想要:
<div ng-class="{'true': true}">
Run Code Online (Sandbox Code Playgroud)
您可能想要使用:
<div ng-class="item.name"></div>