There is the following code:
HTML:
<tr ng-repeat="o in orders" ng-class="getOrderClass(o)">
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'. 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
If this syntax is used then class attribute will have class name along with expression used to calculate this 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. 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.
It could be something like <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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.