使用AngularJS動態設置CSS大致有2種思路:
1、通過動態設置class名稱
比如先定義2個樣式:
.show-true{
display:block;
}
.show-flase{
display:none;
}
在某個元素中:
<div class="show-{{temp}}".....
temp為$scope的一個變量,通過設置$scope.temp = true 或 $scope.temp = false來決定temp變量的具體值。
比如:
<!doctype html><html ng-app="myApp"><head><meta charset="UTF-8"><title>Untitled Document</title><style>.menu-disabled-true{color: gray;}.menu-disabled-false{color: red;}</style><script src="angular.min.js"></script><script>var myApp = angular.module("myApp",[]);myApp.controller("MyController", function($scope){$scope.isDisabled = false;$scope.changeState = function(){$scope.isDisabled = true;};});</script></head><body ng-controller="MyController"><ul><li class="menu-disabled-{{isDisabled}}" ng-click="changeState()">hello</li></ul></body></html>
2、使用ng-class
ng-class顯示一個對象,比如ng-class="{selected: true}"表示class="selected"。
以下ng-class的字段直接接收bool值。
<!doctype html><html ng-app="myApp"><head><meta charset="UTF-8"><title>Untitled Document</title><style>.error{background-color: red;}.warning{background-color: yellow;}</style><script src="angular.min.js"></script><script>var myApp = angular.module("myApp",[]);myApp.controller("MyController",function($scope){$scope.isError = false;$scope.isWarning = false;$scope.showError = function(){$scope.messageText = "error";$scope.isError = true;$scope.isWarning = false;};$scope.showWarning = function(){$scope.messageText = "warning";$scope.isError = false;$scope.isWarning = true;};});</script></head><body ng-controller="MyController"><div ng-class="{error:isError, warning:isWarning}">{{messageText}}</div><button ng-click="showError()">顯示error</button><button ng-click="showWarning()">顯示warning</button></body></html>
以下,ng-class的字段接收一個返回bool類型的表達式。
<!doctype html><html ng-app="myApp"><head><meta charset="UTF-8"><title>Untitled Document</title><style>.selected{background-color: lightgreen;}</style><script src="angular.min.js"></script><script>var myApp = angular.module("myApp",[]);myApp.controller("MyController",function($scope){$scope.person =[{name: 'darren', age: '20'},{name: 'jack', age: '23'}];$scope.selectPerson = function(rowIndex){$scope.selectedRow = rowIndex;};});</script></head><body><table ng-controller="MyController"><tr ng-repeat="p in person" ng-click="selectPerson($index)" ng-class="{selected: $index==selectedRow}"><td>{{p.name}}</td><td>{{p.age}}</td></tr></table></body></html>
參考資料:<<用AngularJS開發下一代Web應用>>
