In this article I will explain with an example, how to use
ng-focus directive in
AngularJS.
HTML Markup
The following HTML Markup consists of:
DIV – For applying
ng-app and
ng-controller AngularJS directives.
TextBox – For capturing user input.
The HTML INPUT TextBox has been assigned with the following
AngularJS directives.
ng-style – For applying CSS styles to the TextBox.
ng-focus – Called when TextBox gets focus.
ng-blur – Called when TextBox loses 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-focus Directive
Inside the HTML Markup, the following
AngularJS script file 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
Demo
Downloads