AngularJS ngFocus Directive



  • ng-focus directive is used to specify the custom behavior that execute when an HTML element gets focus.
  • In AngularJS, the ng-focus directive will not override the HTML element’s original onfocus event, both will be executed.
  • The ng-focus directive is compiling at the priority level “0” (zero is a default priority level).
  • ng-focus is supported by <a>, <input>, <select>, <textarea> tags and window object.

Syntax for ng-focus directive in AngularJS:

<element ng-focus= "expression"></element>

Parameter value for ng-focus directive in AngularJS:

Value Description
expression It is used to define an expression that execute when an HTML element gets focus.

Sample coding for ng-focus directive in AngularJS:

 Tryit<!DOCTYPE html>
<html>
    <head>
        <title>Wikitechy AngularJS Tutorials</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/
                    angular.min.js"> </script>
        </head>
        <body ng-app="">
            <h2>Wikitechy ng-focus Directive in AngularJS Tutorials</h2>
            <lable>Enter the text:</lable>
            <input ng-focus="count = count + 1" ng- init="count=0">
            <h3>count = {{ count }}</h3>
            <h3>The "count" variable value will be increased when the input 
                field gets focus.</h3>
        </body>
</html>

Code Explanation for ng-focus directive in AngularJS:

Code Explanation for AngularJS ngFocus Directive

  1. AngularJS is distributed as a JavaScript file, and can be added to a HTML page with a <script> tag.
  2. The AngularJS application is defined by ng-app=" ". The application runs inside the <body> tag. It’s also used to define a <body> tag as a root element.
  3. The ng-focus= “count=count+1” is used to increase the count variable by one, when the input field gets focus.
  4. The ng-init="count = 0" is used to define the initial value of the count variable is “0”.
  5. The {{ count }} is used to dynamically bind the count variable value when the input field gets focus.

Sample Output for ng-focus directive in AngularJS

Sample Output for AngularJS ngFocus Directive

  1. The output displays that the input field gets focus and the content “Count=1”. Here the variable “count” will be increased a value by 1, because only one time the input field gets focus.

Related Searches to angularjs ngFocus directive