ng-focus example in angularjs


      ng-focus directive executes when an element gets focus. This can be used in many different ways and below I have represented few of the examples.

ng-focus syntax

Example 1 - Input field gets focus
<!DOCTYPE html>
<script src=""></script>
<body ng-app="">

<input ng-focus="count = count + 1" ng-init="count=0" />


<p>Move your mouse and focus the textbox with left click</p>


This piece of code is quite self explanatory.


Example 2 -  Change property when input field gets focus

<!DOCTYPE html>
 <div ng-app="myApp" ng-controller="myctrl">
  Enter Text: <input type="text" ng-focus="focusEvent()" ng-blur="blurEvent()" /><br />
  <br />

 <script type="text/javascript">
  var app = angular.module('myApp', []);
  app.controller('myctrl', function($scope) {
   $scope.focusEvent = function() {
    $scope.message = "Got focus";
   $scope.blurEvent = function() {
    $scope.message = "Lost focus";


We have two events, ng-focus will assign value "Got focus", when the focus is lost, ng-blur event is triggered which will assign "Lost focus" value. More more details on ng-blur event, check this link


Hope these examples helps..

No comments:
Write comments

Popular Posts