當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


AngularJS ng-class用法及代碼示例


AngularJS中的ng-class指令用於指定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">GeeksforGeeks</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]"> 
            GeeksforGeeks 
        </span>  
        is the computer science portal for geeks. 
    </div> 
</body> 
  
</html>                    

輸出:
單擊按鈕之前:
ngclass
單擊樣式按鈕後:
ngclass

範例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">GeeksforGeeks</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>                    

輸出:
選擇元素之前:
ngclass
選擇元素後:
ngclass



相關用法


注:本文由純淨天空篩選整理自Vishal Chaudhary 2大神的英文原創作品 AngularJS | ng-class Directive。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。