angular.js ng-class 使用
ng-class 常见三种使用方式:
- 通过 scope 绑定
//1、通过$scope绑定(不推荐):
function ctrl($scope) {
$scope.className = "selected";
}
<div class="{{className}}"></div>
- 2、通过对象数组绑定:
function ctrl($scope) {
$scope.isSelected = true;
}
<div ng-class="{true:'selected',false:'unselected'}[isSelected]"></div>
当isSelected为true时,增加selected样式;当isSelected为false时,增加unselected样式。
- 通过key/value键值对绑定:
function ctrl($scope) {
$scope.isA = true;
$scope.isB = false;
$scope.isC = false;
}
<div ng-class="{'A':isA,'B':isB,'C':isC}"></div>
当isA为true时,增加A样式;当isB为true时,增加B样式;当isC为true时,增加C样式。
- 通过ng-repeat 绑定
.selected {background-color: lightgreen;}
<html ng-app="myApp">
<head>
<title>CSS实例3</title>
<link rel="stylesheet" type="text/css" href="css/menu03.css" />
</head>
<body>
<table ng-controller="RestaurantTableController">
<tbody>
<tr ng-repeat="restaurant in directory" ng-click="selectRestaurant($index)" ng-class="{selected: $index==selectedRow}">
<td>{{restaurant.name}}</td>
<td>{{restaurant.cuisine}}</td>
</tr>
</tbody>
</table>
<script src="lib/angular/angular.js"></script>
$scope.directory=[{name:'The Handsome Heifer',cuisine: 'BBQ'},
Fine Fish',cuisine: 'Seafood'}];
$scope.selectRestaurant=function(row) {$scope.selectedRow=row;};});</script>
</body>
</html>
本文介绍了AngularJS中ng-class指令的三种常见使用方法:通过scope变量绑定、通过对象数组绑定以及通过key/value键值对绑定。同时,还展示了如何在实际项目中利用ng-class结合ng-repeat来实现表格行的选择效果。
3667

被折叠的 条评论
为什么被折叠?



