可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have the component and have a problem setting the css class to it. I want it to always have a class of "box", then to have additional classes specified by the directive "class" argument and one conditional class "mini".
Conceptually what I want to achieve is something like this:
...
The problem is that when I set the class html attribute, the ng-class attribute is omitted. How to make my example work without changing the controller? Is it even possible, or should I set the class in the controller instead (which I wish to avoid)?
回答1:
I needed multiple classes where one was $scope derived and others were literal classes. Thanks to the hint from Andre, below worked for me.
{{workStream.Name}}
回答2:
A quick solution would be define the box class inside ng-class attribute:
If you want to include a scope variable as a class, you can't use ng-class:
Angular expressions do not support the ternary operator, but it can be emulated like this:
condition && (answer if true) || (answer if false)
回答3:
Edit: for newer versions of Angular see Nitins answer as it is the best one atm
For me, this worked (I'm working on AngularJS v1.2.14 at the moment so I guess 1.2.X+ should support this, not sure about the earlier versions):
I replaced your {{class}}
with {{myScopedObj.classesToAdd}}
to show that any scoped variable or even a bit more complex object can be used this way.
So, every DIV element crated this way will have "box" class and any class contained within myScopedObj.classesToAdd
(useful when using ng-repeat and every element in the array needs to have a different class applied), and it will have the "mini" class if !isMaximized
.
回答4:
Another way to do this without double curly braces and includes scope variables, tested with angular v1.2+.
It's also rather nice because the variable can use different types as a index without increasing complexity using ternaries. It can also remove any need for negations ;) Here is a fiddle link
回答5:
You can use simple expression given below
ng-class="{'active' : itemCount, 'activemenu' : showCart}"