AngularJS ng类指令用法详细介绍

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 = "https://www.lsbin.com/Style" /> < input type = "button" ng-click = "edit=false" value = "https://www.lsbin.com/Reset" /> < br > < br > < span ng-class = "{true:'edit'}[edit]" > lsbin < / span > is the computer science portal for geeks. < / div > < / body > < / html >

输出如下:
单击按钮之前:
AngularJS ng类指令用法详细介绍

文章图片
单击样式按钮后:
AngularJS ng类指令用法详细介绍

文章图片
范例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 >

输出如下:
选择元素之前:
AngularJS ng类指令用法详细介绍

文章图片
【AngularJS ng类指令用法详细介绍】选择元素后:
AngularJS ng类指令用法详细介绍

文章图片

    推荐阅读