有条件地应用课程的最佳方法是什么? [英] What is the best way to conditionally apply a class?
问题描述
假设您有一个在 ul
中呈现的数组,每个元素都有一个 li
,控制器上有一个名为 selectedIndex
的属性.在 AngularJS 中使用索引 selectedIndex
将类添加到 li
的最佳方法是什么?
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?
我目前正在(手动)复制 li
代码并将类添加到 li
标记之一并使用 ng-show
和 ng-hide
使每个索引只显示一个 li
.
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 类名放入 Controller 中,这里有一个我从 v1 之前的日子开始使用的老技巧.我们可以编写一个直接计算为类名的表达式selected,不需要自定义指令:
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}"
Angular 现在支持返回对象的表达式.此对象的每个属性(名称)现在都被视为一个类名,并根据其值进行应用.
Angular now supports expressions that return 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 类保留在控制器代码之外.
We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time keep CSS classes out of Controller code.
这篇关于有条件地应用课程的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!