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

Dav*_*ica 17 css angularjs angularjs-directive

ng-classng-style这两个似乎是动态创建CSS类的方法.他们之间有什么区别?

hal*_*ilb 27

ng-style用于将javascript对象插入到style属性中,而不是css类.

以下指令将被翻译为style ="color:red"

ng-style="{color: 'red'}"
Run Code Online (Sandbox Code Playgroud)

NG-类指令转换你的对象到属性.

isDeleted变量为true时,以下内容将被转换为class ="deleted".

ng-class="{'deleted': isDeleted}"
Run Code Online (Sandbox Code Playgroud)

注意:

还有一个用于ng-style的用例.如果要在样式属性中插入某些内容,则应考虑使用ng-style.否则,在文档建议的Internet Explorer 11之前,这将无效.

所以,而不是使用样式:

style="width: {{progress}}"
Run Code Online (Sandbox Code Playgroud)

使用ng-style:

ng-style="{'width':progress}"
Run Code Online (Sandbox Code Playgroud)


小智 6

您正在ng-class加载在某个地方定义的 CSS 类,例如 Bootstrap。您正在ng-style设置您希望该元素具有的 CSS 样式,例如:

\n\n
ng-style="{ \'background-color\': person.email == selectedPerson.email ? \'lightgray\' : \' \'}" //background-color is a style\n
Run Code Online (Sandbox Code Playgroud)\n\n

has-error是在某处定义的由样式组成的类:

\n\n
ng-class="{ \'has-error\xe2\x80\x99: !theForm.email.$valid, \'has-success\':theForm.email.$valid}\n
Run Code Online (Sandbox Code Playgroud)\n