ng-class

ng-class 指令允许动态设置CSS类在一个 HTML 元素上,可以动态的修改 class 的值 ---

方法一

<div ng-app="myApp" ng-controller="myAppCon">
	<style>
		.test{
			transition: all 0.5s;
			color: #000;
			font-size: 14px;
		}
		.cls1{
			font-size: 24px;
		}
		.cls2{
			color: red;
		}
	</style>
	<div class="test" ng-class="{ 'cls1' : c1, 'cls2' : c2}">
		点击按钮测试
	</div>
	<hr/>
	<button ng-click="cls1_click(true)">添加 cls1 样式</button>
	<button ng-click="cls1_click(false)">删除 cls1 样式</button>
	<hr/>
	<button ng-click="cls2_click(true)">添加 cls2 样式</button>
	<button ng-click="cls2_click(false)">删除 cls2 样式</button>
</div>
<script>
	angular.module('myApp', [])
		.controller('myAppCon',['$scope',function($scope){
			$scope.cls1_click = function(state){
				$scope.c1 = state;
			}
			$scope.cls2_click = function(state){
				$scope.c2 = state;
			}
		}]);
</script>
当 c1 的值为 true 时则添加 cls1 class,当 c2 为 true 时 添加 cls2 class

方法二

<div ng-app="myApp" ng-controller="myAppCon">
	<style>
		.test{
			transition: all 0.5s;
			color: #000;
			font-size: 14px;
		}
		.cls1{
			font-size: 24px;
		}
		.cls2{
			color: red;
		}
	</style>
	<div class="test" ng-class="{true: 'cls1', false: 'cls2'}[active]">
		点击按钮测试
	</div>
	<hr/>
	<button ng-click="cls1_click(true)">添加 cls1 样式</button>
	<button ng-click="cls1_click(false)">删除 cls1 样式</button>
</div>
<script>
	angular.module('myApp', [])
		.controller('myAppCon',['$scope',function($scope){
			$scope.active = false;
			$scope.cls1_click = function(state){
				$scope.active = state;
			}
		}]);
</script>
当 active 的值为 true 时则添加 cls1 class,当 active 为 false 时 添加 cls2 class

方法三

<div ng-app="myApp" ng-controller="myAppCon">
	<style>
		.test{
			transition: all 0.5s;
			color: #000;
			font-size: 14px;
		}
		.cls1{
			font-size: 24px;
		}
		.cls2{
			color: red;
		}
	</style>
	<div class="test {{ classname }}">
		点击按钮测试
	</div>
	<hr/>
	<button ng-click="cls1_click('cls1')">添加 cls1 样式</button>
	<button ng-click="cls1_click('clas2')">添加 cls2 样式</button>
</div>
<script>
	angular.module('myApp', [])
		.controller('myAppCon',['$scope',function($scope){
			$scope.cls1_click = function(classname){
				$scope.classname = classname;
			}
		}]);
</script>
使用双向绑定的方式,动态修改 class 的值