[英]Angular ng-class dynamic CSS
There is the following code: 有以下代码:
HTML: HTML:
<tr ng-repeat="o in orders" ng-class="getOrderClass(o)">
CoffeeScript: CoffeeScript:
$scope.getOrderClass = (o) ->
switch o.orderStatus.title
when 'New' then 'new-order'
when 'Completed' then 'completed-order'
It code looks good, but there is one problem: After page loading I see 'new-order' class or 'completed-order' class in 'ng-class' attribute, not in 'class'. 它的代码看起来不错,但是有一个问题:页面加载后,我在'ng-class'属性而不是'class'中看到了'new-order'类或'completed-order'类。 Where is the mistake?
错误在哪里? Thanks in advance
提前致谢
您可以使用该结构
ng-class="{'new-order' : o.orderStatus.title == 'New', 'completed-order' : o.orderStatus.title == 'Completed'}"
You have used ng-class as an attribute in this case If you inspect or view source then it would be listed as value of ng-class attribute If you need the calculated class value in "class" attribute, then use this syntax 在这种情况下,您已使用ng-class作为属性。如果您检查或查看源,则它将被列为ng-class属性的值。如果需要在“ class”属性中计算出的类值,则使用此语法
If this syntax is used then class attribute will have class name along with expression used to calculate this class 如果使用此语法,则class属性将具有类名称以及用于计算该类的表达式
Try this: 尝试这个:
$scope.getOrderClass = (o) ->
title = o.orderStatus.title
{
'new-order': title == 'New'
'completed-order': title == 'Completed'
}
You could write a directive like this 您可以编写这样的指令
app.directive('myClass', [function(){
return {
scope: {
class: '=myClass'
},
restrict: 'A',
link: function(scope, elem, attrs, controller) {
elem.addClass(scope.class);
}
};
}]);
In view: 鉴于:
<div my-class="getOrderClass(o)">I have the getOrderClass(o) class</div>
I would suggest you somehow cache the result of getOrderClass(o), because when you bind a function call, it will get called on each digest circle. 我建议您以某种方式缓存getOrderClass(o)的结果,因为绑定函数调用时,它将在每个摘要循环上被调用。 This can cause performance issues in the long run and is usually not a good practice, especially if the function is in an ng-repeat.
从长远来看,这可能会导致性能问题,通常不是一个好习惯,特别是如果该功能处于ng-repeat模式下。
It could be something like <div ng-repeat="o in orders" my-class="orderClasses[o.id]">I have the getOrderClass(o) class</div>
可能类似于
<div ng-repeat="o in orders" my-class="orderClasses[o.id]">I have the getOrderClass(o) class</div>
Edit: notice that this directive only adds the class once, when the directive is initialized so it won't work like normal two way binding. 编辑:请注意,该指令在初始化时仅添加一次该类,因此它不会像普通的双向绑定那样工作。 If you'd like that you also have to add a watcher for scope.class and call elem.addClass again
如果您愿意,还必须为scope.class添加观察者,然后再次调用elem.addClass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.