angularjs – ng-class 指令

angularjsweb developmentfront end technology更新于 2026/1/6 23:52:17

angularjs 中的 ng-class 指令 允许用户通过数据绑定表达式来动态设置 HTML 元素上的 CSS 类,该表达式将进一步表示所有要添加的类。只有当 ngClass 指令中的表达式返回 True 时,才会添加该类,否则不会添加。所有 HTML 元素都支持该指令。

如果已经设置了重复的类,该指令不会设置任何重复的类。当表达式发生变化时,先前添加的类将被移除,之后才会添加新的类。

语法

<element ng-class="expression">..Content..</element>

示例 − ngClass 指令

在 Angular 项目目录中创建文件"ngClass.html",并复制粘贴以下代码片段。

<!DOCTYPE html>
<html>
   <head>
      <title>ngClass Directive</title>

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/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">
      Welcome to Tutorials Point
   </h1>
   <h2>
      angularjs | ngClass 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]">
            SIMPLY EASY LEARNING
         </span>
      </div>
   </body>
</html>

输出

要运行上述代码,只需打开您的文件并将其作为普通 HTML 文件运行即可。您将在浏览器窗口中看到以下输出。

示例 2

在您的 Angular 项目目录中创建文件"ngClass.html",并复制粘贴以下代码片段。

<!DOCTYPE html>
<html>
   <head>
      <title>ngClass Directive</title>

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">       </script>

      <style>
         .index {
            color: white;
            background-color: green;
         }
      </style>
   </head>

   <body ng-app="app" style="text-align: center;">
      <h1 style="color: green;">
         Welcome to Tutorials Point
      </h1>
      <h2>
         angularjs | ngClass Directive
      </h2>

      <div ng-controller="demo" style="margin-left: auto; margin-right: auto; text-align: center; display: block;">
         <table style="text-align: center;">
            <thead>
               <th>Select any frontend framework:</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 for passing the values and checking... -->
      <script>
      var app = angular.module("app", []);

      app.controller("demo", [
         "$scope",
         function ($scope) {
            $scope.sort = [{ name: "angularjs" }, { name: "ReactJS"}, { name: "VueJS" }];
            $scope.sel = function (index) {
               $scope.row = index;
               };
            },
         ]);
      </script>
   </body>
</html>

输出

要运行上述代码,只需打开您的文件并将其作为普通 HTML 文件运行即可。您将在浏览器窗口中看到以下输出。


相关文章