1、angularjs的表达式是可以写在class里面动态改变其值的,写法如下:
□、CSS1.html:
<!doctype html>
<html ng-app="MyCSSModule">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="CSS1.css">
</head>
<body>
<div ng-controller="CSSCtrl">
<p class="text-{{color}}">测试CSS样式</p> //注意这里的class="text-{{color}}"这个class写法,text-后面的angular表达式变量
<button class="btn btn-default" ng-click="setGreen()">绿色</button>
</div>
</body>
<script src="js/angular-1.3.0.js"></script>
<script src="CSS1.js"></script>
</html>
□、CSS1.css:
.text-red {
background-color: #ff0000;
}
.text-green {
background-color: #00ff00;
}
□、CSS1.js:
var myCSSModule = angular.module(‘MyCSSModule‘, []);
myCSSModule.controller(‘CSSCtrl‘, [‘$scope‘,
function($scope) {
$scope.color = "red";
$scope.setGreen = function() { //定义一个setGreen()方法,点击调用这个方法改变color的值,平谈无奇就这么简单
$scope.color = "green";
}
}
]);
2、上面的例子改造一下,用ng-class,写法如下:
□、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> //注意ng-class=‘{error: isError, warning: isWarning}‘的写法,后面的表达式意为:
当isError为true时,调用error样式类,当isWarning为true时,调用warning样式类
<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.css:
.error {
background-color: red;
}
.warning {
background-color: yellow;
}
□、NgClass.js:
var myCSSModule = angular.module(‘MyCSSModule‘, []);
myCSSModule.controller(‘HeaderController‘, [‘$scope‘,
function($scope) {
$scope.isError = false;
$scope.isWarning = false; //两个标记变量默认状态下都为false
$scope.showError = function() { //控制器里面做的事就是给变量赋值,通过html中的ng-click来调用赋值的方法
$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;
};
}
])