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
<ng-focus
  ng-focus="expression">
...
</ng-focus>

Example 1 - Input field gets focus
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">

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

<h1>{{count}}</h1>

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

</body>
</html>

This piece of code is quite self explanatory.

Output

Example 2 -  Change property when input field gets focus

<!DOCTYPE html>
<html>
<head>
<title></title>
<script
 src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
 <div ng-app="myApp" ng-controller="myctrl">
  Enter Text: <input type="text" ng-focus="focusEvent()" ng-blur="blurEvent()" /><br />
  <br />
  <p>{{message}}</p>
 </div>

 <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";
   }
   
  });
 </script>

</body>
</html>

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

Output


Hope these examples helps..



Reactions:

0 comments :

Post a Comment