angularjs – 如何使用ngClass的动态值
发布时间:2020-12-17 09:17:58 所属栏目:安全 来源:网络整理
导读:我试图应用与一个作用域变量相同的类名. 例如: divng-class =“{item.name:item.name}” 所以item.name的值被添加到类中.这似乎什么都不做.有什么建议如何做到这一点? 谢谢! 编辑: 这实际上是在选择中使用ng选项来完成的.例如: select ng-options =“c
我试图应用与一个作用域变量相同的类名.
例如: < divng-class =“{item.name:item.name}”> 所以item.name的值被添加到类中.这似乎什么都不做.有什么建议如何做到这一点? 谢谢! 编辑: 这实际上是在选择中使用ng选项来完成的.例如: < 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); } }); }); }); } }; }]);
比以往更好.
<div ng-class="{'{{item.name}}' : item.condition}"> 是. ‘和{{for classname. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |