1.第一种方法效果图CSS1.html<!doctype html><html ng-app="MyCSSModule"><head> <meta charset="utf-8"> <li
1.第一种方法
效果图
CSS1.html
<!doctype html><html ng-app="MyCSSModule"><head> <meta charset="utf-8"> <link rel="stylesheet" href="css/CSS1.css"></head><body><div ng-controller="CSSCtrl"> <p class="text-{{color}}">测试CSS样式</p> <button class="btn btn-default" ng-click="setGreen()">绿色</button></div></body><script src="js/angular-1.3.0.js"></script><script src="js/CSS1.js"></script></html>
CSS1.js
var myCSSModule = angular.module('MyCSSModule', []);myCSSModule.controller('CSSCtrl', ['$scope', function ($scope) { $scope.color = "red"; $scope.setGreen = function () { $scope.color = "green"; } }]);
CSS1.css
.text-red { background-color: #ff0000;}.text-green { background-color: #00ff00;}
这种改变样式的方法中如果<p class="text-{{color}}">测试CSS样式</p>
中color
没有获取到会出现问题,推荐使用下面这种方法<br/>
2.第二种方法
效果图
NgClass.html
<!doctype html><html ng-app="MyCSSModule"><head> <meta charset="utf-8"> <link rel="stylesheet" href="NgClass.css"></head><body><div ng-controller='HeaderController'> <div ng-class='{error: isError, warning: isWarning}'>{{messageText}}</div> <button ng-click='showError()'>Simulate Error</button> <button ng-click='showWarning()'>Simulate Warning</button></div></body><script src="js/angular-1.3.0.js"></script><script src="NgClass.js"></script></html>
NgClass.js
var myCSSModule = angular.module('MyCSSModule', []);myCSSModule.controller('HeaderController', ['$scope', function ($scope) { $scope.isError = false; $scope.isWarning = false; $scope.showError = function () { $scope.messageText = 'This is an error!'; $scope.isError = true; $scope.isWarning = false; }; $scope.showWarning = function () { $scope.messageText = 'Just a warning. Please carry on.'; $scope.isWarning = true; $scope.isError = false; }; }]);
NgClass.css
.error { background-color: red;}.warning { background-color: yellow;}