ng-class 和 ng-style 有什么区别?
ng-class
和 ng-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.
当 isDeleted 变量为 true 时,以下内容将被转换为 class="deleted".
Following will be translated to class="deleted" when isDeleted variable is true.
ng-class="{'deleted': isDeleted}"
注意:
ng-style 还有一个用例.如果你想在 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 风格:
ng-style="{'width':progress}"