AngularJS 是一个 JavaScript 框架. 它可通过 <script> 标签添加到 html 页面. AngularJS 通过 指令 扩展了 HTML, 且通过 表达式 绑定数据到 HTML.
使用 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>
来源: http://www.css88.com/qa/angular-js/12018.html