ng级指令在AngularJS中, 用于指定HTML元素上的CSS类。它用于动态绑定HTML元素上的类。如果ng-class指令中的表达式返回true, 则仅添加该类, 否则不添加。所有HTML元素都支持它。
语法如下:
<element ng-class="expression"> Contents... </element>
范例1:本示例使用ng-class指令设置和重置CSS类。
<!DOCTYPE html>
< html >
< head >
< title >ng-class Directive</ title >
< script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js" >
</ script >
< style >
.edit {
color: green;
font-size: 1.5em;
}
</ style >
</ head >
< body ng-app = "" style = "text-align:center" >
< h1 style = "color:green" >lsbin</ h1 >
< h2 >ng-class Directive</ h2 >
< div >
< input type = "button" ng-click = "edit=true" value = "Style" />
< input type = "button" ng-click = "edit=false" value = "Reset" />
< br >< br >
< span ng-class = "{true:'edit'}[edit]" >
lsbin
</ span >
is the computer science portal for geeks.
</ div >
</ body >
</ html >
输出如下:
单击按钮之前:
单击样式按钮后:
范例2:本示例使用ng-class指令将CSS样式设置为该类。
<!DOCTYPE html>
< html >
< head >
< title >ng-class Directive</ title >
< script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js" >
</ script >
< style type = "text/css" >
.index {
color: white;
background-color: green;
}
</ style >
</ head >
< body ng-app = "app" style = "padding:20px" >
< h1 style = "color:green" >lsbin</ h1 >
< h2 >ng-class Directive</ h2 >
< div ng-controller = "geek" >
< table >
< thead >
< th >Select any sorting technique:</ th >
< tr ng-repeat = "i in sort" >
< td ng-class = "{index:$index==row}"
ng-click = "sel($index)" >
{{i.name}}
</ td >
</ tr >
</ thead >
</ table >
</ div >
< script >
var app = angular.module("app", []);
app.controller('geek', ['$scope', function ($scope) {
$scope.sort = [
{ name: "Merge sort" }, { name: "Quick sort" }, { name: "Bubble sort" }
];
$scope.sel = function (index) {
$scope.row = index;
};
}]);
</ script >
</ body >
</ html >
输出如下:
选择元素之前:
选择元素后: