javascript 在使用混合表达式时使用带有 angular 和 ng-class 的类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25089350/
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
Using class with angular vs ng-class while using a mixed expression
提问by user264230
I have a div that I want to give a dynamic class with AngularJS.
我有一个 div,我想用 AngularJS 给一个动态类。
The div is withing an ng-repeat statement where lang.prefix is first en then sv
div 带有一个 ng-repeat 语句,其中 lang.prefix 首先是 en 然后是 sv
Using the following code works and sets the class to i-flag-en than i-flag-sv, but is it correct?
使用以下代码有效并将类设置为 i-flag-en 而不是 i-flag-sv,但它是否正确?
<div class="float-left flag i-flag-{{lang.prefix}}"></div>
I know there exist a ng-classdirective which can be used to dynamically set the class of an element with AngularJS.
我知道存在一个ng-class指令,可用于使用 AngularJS 动态设置元素的类。
I think I read somewhere in a book, that the normal class directive not should be used to set the class property dynamically with AngularJS because of the way Angular manipulates the dom.
我想我在一本书的某个地方读到过,由于 Angular 操纵 dom 的方式,不应该使用普通的 class 指令来使用 AngularJS 动态设置 class 属性。
However, the following code does not work:
但是,以下代码不起作用:
<div class="float-left flag" ng-class="i-flag-{{lang.prefix}}"></div>
and I rather want to set the class in this way instead of creating another scope variable.
我宁愿以这种方式设置类,而不是创建另一个作用域变量。
Is it bad practice to use the class attribute with AngularJS to dynamically set the class? Does it work all the time even if it would be bad practice?
使用带有 AngularJS 的 class 属性来动态设置类是不好的做法吗?即使这是不好的做法,它是否一直有效?
回答by ryeballar
The book you have mentioned may have talked about the problems of using ng-class
and class {{}}
interpolations together wherein updates in the interpolation removes the ng-class
classes, this problem has already been resolved, reference. Thus, using interpolation within class attributes is totally fine, and does not break good practice because both has its own quirks.
你提到的那本书可能讲了一起使用ng-class
和类{{}}
插值的问题,其中插值中的更新删除了ng-class
类,这个问题已经解决了,参考。因此,在类属性中使用插值是完全可以的,并且不会破坏良好的实践,因为两者都有自己的怪癖。
Your usage of ng-class however is incorrect, you have to concatenate the literal string value with your scope string variable:
但是,您对 ng-class 的使用是不正确的,您必须将文字字符串值与范围字符串变量连接起来:
<div class="float-left flag" ng-class="'i-flag-' + lang.prefix"></div>
but I think it is much preferable to use your first example instead:
但我认为最好使用你的第一个例子:
<div class="float-left flag i-flag-{{lang.prefix}}"></div>