在angular中为我们提供了3种方案处理class:
1:scope变量绑定。(不推荐使用)
2:字符串数组形式。
3:对象key/value处理。
我们继续其他两种解决方案:
1字符串数组形式是针对class简单变化,具有排斥性的变化,true是什么class,false是什么class,其形如:
<!DOCTYPE html>
<html lang="en" ng-app="">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.active{background: green}
.active{background: red}
</style>
</head>
<body>
<div ng-controller="Aaa">
<div ng-class="{ true: 'active', false: 'inactive'}[isActive]">
11111
</div>
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
function Aaa($scope){
$scope.isActive=true;
}
</script>
</body>
</html>
其结果是2中组合,isActive表达式为true,则 active,负责inactive。
扩展:
<!DOCTYPE html>
<html lang="en" ng-app="">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.active{background: green}
.inactive{background: red}
</style>
</head>
<body>
<div ng-controller="Aaa">
<div ng-class="{ true: 'active', false: 'inactive'}[isActive]" ng-click="change()">
11111
</div>
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
function Aaa($scope){
$scope.isActive=true;
$scope.change=function(){
$scope.isActive=!$scope.isActive
}
}
</script>
</body>
</html>
这种方法做到了class之间简单的切换
2对象key/value处理主要针对复杂的class混合,其形如:
<!DOCTYPE html>
<html lang="en" ng-app="">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.selected{background: green}
.car{border:1px solid red}
</style>
</head>
<body>
<div ng-controller="Aaa">
<div ng-class="{'selected' : isSelected, 'car' : isCar}">
11111
</div>
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
function Aaa($scope){
$scope.isSelected=true;
$scope.isCar=true;
}
</script>
</body>
</html>
当 isSelected = true 则增加selected class,
当isCar=true,则增加car class,