Javascript ng-class 中的表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14024448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
expression inside ng-class
提问by jonhobbs
I have a very simple Angular App and I'm trying to use ng-repeat in conjunction with ng-class to repeat a template and apply a different class to the outer div depending on one of the properties of the data being bound.
我有一个非常简单的 Angular 应用程序,我正在尝试将 ng-repeat 与 ng-class 结合使用来重复模板并将不同的类应用到外部 div,具体取决于被绑定数据的属性之一。
this worked when I used a simple...
当我使用一个简单的...
ng-class="message.type"
...but unfortunately I need to concatenate a string to the start of the message type.
...但不幸的是,我需要将一个字符串连接到消息类型的开头。
I tried to create a JSfiddle here...
我试图在这里创建一个 JSfiddle ......
... but it's my first attempt at making a JSfiddle too and I must be doing something wrong because the Angular stuff doesn't seem to be running. It does show what I'm trying to do with the expression though.
...但这也是我第一次尝试制作 JSfiddle,我一定是做错了什么,因为 Angular 的东西似乎没有运行。不过,它确实显示了我试图用表达式做什么。
Any help would really be appreciated.
任何帮助将不胜感激。
回答by mpm
html :
html :
<div ng-controller="mainCtrl">
<div ng-repeat="message in data.messages" ng-class="'className-' + message.type">
Repeat Me
</div>
</div>
</div>
javascript :
javascript :
var mainCtrl=function($scope) {
$scope.data = {}
$scope.data.messages = [
{
"type": "phone"},
{
"type": "email"},
{
"type": "meeting"},
{
"type": "note"}
]
}?
}?
in the fiddle you put some {{}} around the expression dont do it because it is an expression.
在小提琴中,你在表达式周围放了一些 {{}} 不要这样做,因为它是一个表达式。
回答by Mark Rajcok
FYI, an alternative to what @camus answered:
仅供参考,@camus 回答的替代方案:
class="{{'className-' + message.type}}"
When using class, the expression (inside {{}}s) must evaluate to a string of space-delimited class names.
使用时class,表达式(在 {{}} 中)必须计算为一串以空格分隔的类名。
When using ng-class, the expression must evaluate to one of the following:
使用 时ng-class,表达式的计算结果必须为以下之一:
- a string of space-delimited class names, or
- and array of class names, or
- a map/object of class names to boolean values.
- 一串以空格分隔的类名,或
- 和类名数组,或
- 类名到布尔值的映射/对象。

