AngularJS ng-focus Event with Example

Here we will learn ng-focus event directive in angularjs, use of ng-focus event directive in angularjs, change textbox background color with ng-focus event in angularjs with example.

AngularJS ng-focus Event Directive

In angularjs ng-focus event directive is used to define or execute custom behaviour functions whenever input field gets focus.

 

Suppose in angularjs if you want to change textbox colour on focus or call some custom functions on input field focus it’s better to use ng-focus event.

Syntax of AngularJS ng-focus Events

Following is the syntax of using angularjs ng-focus event directives in applications.

 

<element ng-focus="expression">

--Your Code--

</element>

The ng-focus event in angularjs will support window object, <input>, <select>, <textarea>, <a> elements. The angularjs ng-focus event will not override onfocus event of html elements both will execute separately.

Example of AngularJS ng-focus Event

Following is the example of changing textbox background colour whenever textbox gets focus using ng-focus event in angularjs application.

 

Live Preview

<!DOCTYPE html>

<html>

<head>

<title>

AngularJs ng-focus Event with Example

</title>

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

<script type="text/javascript">

var app = angular.module('ngfocusApp', []);

app.controller('ngfocusCtrl', function ($scope) {

$scope.focusfn = function () {

$scope.focus = true;

$scope.ftxt='Focused'

}

$scope.blurfn = function () {

$scope.focus = false;

$scope.ftxt = ''

}

});

</script>

<style type="text/css">

.demoFocus

{

background-color: yellow;

}

</style>

</head>

<body>

<div ng-app="ngfocusApp" ng-controller="ngfocusCtrl">

<h2>AngularJS ng-focus Event Example</h2>

Enter Text: <input type="text" ng-class="{ demoFocus: focus}" ng-focus="focusfn()" ng-blur="blurfn()" ng-model="ftxt">

</div>

</body>

</html>

If you observe above angularjs example we are changing textbox colour whenever textbox gets or lost focus using ng-focus and ng-blur event in application.

Output of AngularJS ng-focus Event Example

Following is the result of using ng-focus event in angularjs applications.

 

Angularjs ng-focus event example result or output

 

This is how we can use ng-focus event in angularjs applications to raise event or call functions whenever input field get focus.