angularjs ng-class使用方法
2017-04-13 本文已影响150人
杨杨1314
angularjs 的class有三种用法
1:通过$scope绑定(不推荐) 2:通过对象数组绑定 3:通过key/value键值对绑定
一:通过$scope绑定
controller定义:
![](https://img.haomeiwen.com/i1346252/5bf4f3b521b10e06.jpg)
html使用:
<div class="selected" >hello world</div>
二:通过对象数组绑定
controller定义:
![](https://img.haomeiwen.com/i1346252/db323d219b8c9743.jpg)
html使用:
<div ng-class="{true:'selected',false:'unselected'}[isSelected]">hello world</div>
解释:当isSelected 为true时,增加selected样式;当isSelected为false时,增加unselected样式。
三:通过key/value键值对绑定
controller定义:
![](https://img.haomeiwen.com/i1346252/9637870fb950d7cb.jpg)
html使用:
<div ng-class="{'classA':isA,'classB':isB,'classC':isC}">hello world</div>
解释:当isA为true时,增加classA样式;当isB为true时,增加classB样式;当isC为true时,增加classC样式。
四:说明
1、不推荐第一种方法,因为controller的 $scope应该只有数据和行为
2、ng-class是增加相关样式,可以和class同时使用