什么是有条件地应用类的最佳方式? [英] What is the best way to conditionally apply a class?

查看:70
本文介绍了什么是有条件地应用类的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆