In this article I will explain with an example, how to use ng-blur directive in AngularJS.
 
 

HTML Markup

The following HTML Markup consists of:
DIV – For applying ng-app and ng-controller AngularJS directives.
Note: If you want to learn more about these directives, please refer my article Introduction to AngularJS.
 
TextBox – For user input.
The HTML TextBox has been assigned with following AngularJS directives.
ng-style – For applying CSS styles to the TextBox.
ng-blur – Called when TextBox loses focus.
ng-focus – Called when TextBox gets focus.
<div ng-app="MyApp" ng-controller="MyController">
    <input type="text" value="ASPSnippets" ng-style="Style"
           ng-blur="SetStyle()" ng-focus="RemoveStyle()" />
</div>
 
 

Implementing ng-blur Directive

Inside the HTML Markup, the following AngularJS script is inherited:
1. angular.min.js
Then inside the Controller, a scope variable with name Style is defined with default CSS style which will be applied to the TextBox when page loads.
When the TextBox is focused out, the SetStyle function is called and CSS style i.e. red color is set in Style scope variable.
And, when the TextBox is in focused, the RemoveStyle function is called and CSS style i.e. black color is set in Style scope variable.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript">
    var app = angular.module('MyApp', [])
    app.controller('MyController', function ($scope) {
        // By default Red Color.
        $scope.Style = { "color": "red", "font-weight": "bold" };
        $scope.SetStyle = function () {
            // Set Color to Red.
            $scope.Style = { "color": "red", "font-weight": "bold" };
        }
 
        $scope.RemoveStyle = function () {
            // Set Color to Black.
            $scope.Style = { "color": "black", "font-weight": "bold" };
        }
    });
</script>
 
 

Screenshot

ng-blur example in AngularJS
 
 

Demo

 
 

Downloads