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.
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.
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.
Following is the example of changing textbox background colour whenever textbox gets focus using ng-focus event in angularjs application.
<!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.
Following is the result of using ng-focus event in angularjs applications.
This is how we can use ng-focus event in angularjs applications to raise event or call functions whenever input field get focus.