什么是有条件地应用类的最佳方式? [英] What is the best way to conditionally apply a class?
问题描述
假设你有一个在 UL
渲染与里
每个元素和属性的数组所谓控制器上的的selectedIndex
。什么是一类添加到最好的办法丽
在AngularJS指数的selectedIndex
?
Lets say you have an array that is rendered in a ul
with an li
for each element and a property on the controller called selectedIndex
. What would be the best way to add a class to the li
with the index selectedIndex
in AngularJS?
我目前复制(用手)的里
code,并添加类的之一里
标签和使用 NG-节目
和 NG-隐藏
只显示一个里
每个索引。
I am currently duplicating (by hand) the li
code and adding the class to one of the li
tags and using ng-show
and ng-hide
to show only one li
per index.
推荐答案
如果你不想把CSS类名到控制器像我这样做,这里是自pre-V1天,我用一个老把戏。我们可以写一个前pression直接计算为一个类名的选的,没有自定义指令是必要的:
If you don't want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name selected, no custom directives are necessary:
ng:class="{true:'selected', false:''}[$index==selectedIndex]"
的请注意旧的语法与结肠癌。的
还有应用类有条件,像一个新的更好的方式:
There is also a new better way of applying classes conditionally, like:
ng-class="{selected: $index==selectedIndex}"
角现在支持前pressions返回一个对象。这个对象的每个属性(名称)现在被认为是一类名和已应用根据其值
Angular now supports expressions that returns an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.
不过,这些方法在功能上并不相等。下面是一个例子:
However these ways are not functionally equal. Here is an example:
ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"
因此,我们可以重用基本映射模型属性一类的名字,并在同一时间存在的CSS类保持CSS班列控制器code的。
We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time kept CSS classes out of Controller code.
这篇关于什么是有条件地应用类的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!