AngularJS ng-class指令

AngularJS ng-class指令

AngularJS中的ng-class指令是用来指定HTML元素的CSS类。它被用来动态绑定HTML元素上的类。ng-class的值可以是字符串、对象或数组。它必须包含一个以上的类名,如果是字符串,则用空格分隔。如果是一个对象,它将包含键-值对,其中键代表要添加的类的名称&值代表布尔值。如果ng-class指令里面的表达式返回true,那么只有该类被添加,否则就不添加。如果ng-class的值是一个数组,那么它既可以是字符串的组合,也可以是一个数组。它被所有的HTML元素所支持。

语法:

<element ng-class="expression"> 
    Contents... 
</element>
HTML

示例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>
   
    <h3>ng-class Directive</h3>
   
    <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>
HTML

输出:

AngularJS ng-class指令

示例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>
   
    <h3>ng-class Directive</h3>
   
    <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>
HTML

输出:

AngularJS ng-class指令

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册