ng-class和ng-style有什么区别?

问题描述:

ng-classng-style似乎都是动态设置CSS类的方法.它们之间有什么区别?

ng-class and ng-style both seem to be methods of dynamically setting CSS classes. What is the difference between them?

ng-style 将JavaScript对象插入到 style 属性(而不是CSS类)中.

ng-style is used to interpolate javascript object into style attribute, not css class.

以下指令将转换为 style ="color:red"

ng-style="{color: 'red'}"

ng-class 指令会将您的对象转换为 class 属性.

And ng-class directive translates your object into class attribute.

以下内容将转换为 class ="deleted" .

ng-class="{'deleted': isDeleted}"

注意:

还有另一种ng风格的用例.如果要在style属性中插值,则应考虑使用ng-style.否则,这将无法按照文档的建议在Internet Explorer 11之前运行.

Note:

There is one more use case for ng-style. If you want to interpolate something in style attribute, you should consider using ng-style. Otherwise, that would not work before Internet Explorer 11 as documentation suggests.

因此,不要使用样式:

style="width: {{progress}}"

使用ng-style:

Use ng-style:

ng-style="{'width':progress}"