AngularJS – ng-blur Directive


The ng-blur Directive in AngularJS is fired when an element loses focus from that element. The blur event is executed synchronously along with the DOM manipulations (like removing from the focus point).

AngularJS also executes the expression using scope.$evalAsync if the event is fired during an $apply to ensure the consistent application state.

Syntax

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

Example 1 − ng-blur Directive

Create a file "ngBlur.html" in your Angular project directory and copy-paste the following code snippet.

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

      <script src="https://ajax.googleapis.com/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>

Output

To run the above code, just go to your file and run it as a normal HTML file. You will see the following output on the browser window.

When the textBox is focussed, the message appears −

Example 2

Create a file "ngBlur.html" in your Angular project directory and copy-paste the following code snippet.

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

      <script src="https://ajax.googleapis.com/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>

Output

To run the above code, just go to your file and run it as a normal HTML file. You will see the following output on the browser window.

Updated on: 06-Oct-2021

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements