Zia
Zia

Reputation: 1011

How to detect focus on Angular 1

I am having multiple input text in form and on ng-focus I am calling a method let's say GetFieldName(). I my angular.js how can I detect that method having the focus on first field or second. How can I validate that withing getFieldName() method to get field which have focus on it.

Upvotes: 1

Views: 47

Answers (1)

Sotos
Sotos

Reputation: 426

The best solution is to make angularJS directive to get the attrs or to make the validation https://docs.angularjs.org/guide/forms

This is solution with controller and $event to get the name attribute from element

var myApp = angular.module('myApp',[]);
myApp.controller('formCtrl', ['$scope', function($scope) {
  $scope.text = "sample text";
  $scope.getName = function(event){
   $scope.text = event.target.getAttribute('name');
  };
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div  ng-app="myApp">
<form ng-controller="formCtrl">
{{text }}
<input type="text" name="text1" ng-focus="getName($event)">
<input type="text" name="text2" ng-focus="getName($event)">
<input type="text" name="text3" ng-focus="getName($event)">
<input type="text" name="text4" ng-focus="getName($event)">

</form>
</div>

Upvotes: 2

Related Questions