Hello Friends, In this tutorial we are going to discuss ng-blur directive in Angular. Also, we are going to create an example using ng-blur directive.

Introduction:

The ng-blur directive in angular js is used to specify what to do if an HTML element loses its focus. As like onblur event ng-blur directive is supported by all HTML element like textbox, select, textarea and hyperlink. Also, it doesn’t override the original onblur event.

ng-blur

An example of ng-blur Directive in Angular Js:

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<title>AngularJS Directive Demo</title>
<script src="angular.js"></script>
<style>
b{color:#fa4b2a;}
input[type="text"].onFocus { 
background-color:#44c764; 
} 
input[type="text"].onBlur { 
background-color:#fa4b2a; 
} 
</style>
</head>
<div ng-app>
<input type="text" ng-class="{ demoFocus: focus, demoBlur: blur }" 
ng-focus="focus=true;blur=false;" ng-blur="blur=true;focus=false;">
<!-- ng-blur directive -->
<p>Focus State : <b>{{focus}}</b></p>
<p>Blur State : <b>{{blur}}</b> </p>
</div>
<small>Example of Focus in and out of the input element to fire blur event</small>
</html>

You can view the demo of the application here.

Example2:

I am going to create an example for validating UserName and Password using ng-blur directive.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>Example2</title>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-app="app">
 <div class="container">
 <div ng-controller="debugonwebctrl">
 User Name: <input class="form-control" type="text" ng-blur="userName=false" ng-focus="userName=true">
 <span style="color:red" ng-show="userName">Input your User name</span><br />
 Password: <input class="form-control" type="text" ng-blur="password=false" ng-focus="password=true">
 <span style="color:red" ng-hide="!password">Input your Password</span>
 </div>
 </div>
 <script>
 var app = angular.module("app", []);
 app.controller('debugonwebctrl', ['$scope', function ($scope) {

}]);
</script>
</body>
</html>

You can see the demo of the example here.

Hope you understand this tutorial of Angular Js. We will discuss on the bind-template directive in angular js.

You must take a look at the following links:

Thank You.

Leave a Comment