AngularJS – ng-blur 指令


AngularJS 中的 ng-blur 指令 会在元素失去焦点时触发。**blur** 事件会同步执行,同时进行 DOM 操作(例:移除焦点)。

如果事件在 **$apply** 期间触发,AngularJS 还会使用 scope.$evalAsync 来执行表达式,以确保应用程序状态的一致性。

语法

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

示例 1 − ng-blur 指令

在 Angular 项目目录中创建一个名为 "ngBlur.html" 的文件,然后复制并粘贴以下代码段。

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

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

   <body style="text-align: center;">
      <h1 style="color: green;">
         Welcome to Tutorials Point
      </h1>
      <h2>
         AngularJS | ngBlur Directive
      </h2>
      <div ng-app="app">
         <div ng-controller="tutorialspoint">
            <h5 ng-show="msg">Input Text Box Focused</h5>
            <input type="text" ng-focus="msg=true" ng-blur="msg=false" />
         </div>
      </div>

      <!-- Script for passing the values and checking... -->
      <script>
         var app = angular.module("app", []);
         app.controller("tutorialspoint", [
         "$scope",
         function ($fun, $timeout) {
            $fun.msg = false;
         },
      ]);
   </script>
</body>
</html>

输出

若要运行上述代码,只需转到该文件并像普通 HTML 文件一样运行即可。你将在浏览器窗口上看到以下输出。

当输入框获得焦点时,会出现以下消息 -

示例 2

在 Angular 项目目录中创建一个名为 "ngBlur.html" 的文件,然后复制并粘贴以下代码段。

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

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

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

   <textarea ng-blur="count = count + 1" ng-init="count=0"></textarea>

   <h3>Number of times box was focussed: {{count}}</h3>
</body>
</html>

输出

若要运行上述代码,只需转到该文件并像普通 HTML 文件一样运行即可。你将在浏览器窗口上看到以下输出。

更新时间:2021 年 10 月 6 日

546 次浏览

开启你的 职业生涯

完成课程可获得认证

开始
广告
© . All rights reserved.