AngularJs Set Focus on Input Field


AngularJs Set Focus on Input Field – There are many ways to set Focus on Input Field using AngularJs. Here in this tutorial we are going to explain how you can set focus on input field using the AngularJs. We will explain this with example and demo.


AngularJs Set Focus on Input Field Example

You can set focus on any input of form element simply as below –

AngularJs Set Focus on Input Field: Example

<!DOCTYPE html>
<html lang="en">
<head>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope, $window) {
$scope.setFocus = function() {
 var element = $window.document.getElementById("email");
 element.focus();
};
});
</script> 
</head>
<body>  
<div ng-app="myApp">  
<div ng-controller="myController">  
<input type="text" name="email" id="email" />
<button ng-click="setFocus()">Click To Set Focus</button>  
</div>  
</div> 

</body>  
</html>      
                                                                                                                                                                                                                                                                                                                    

Try it »

We have created a function setFocus() which is called on the button click. $window.document.getElementById(“email”); is used to get element by id, $window service is used to get the element by id.

If you run the above example it will set focus on the input element. The output of the above example will be something like this –

AngularJs Set Focus on Input Field


Advertisements

Add Comment

📖 Read More