Setting Focus on input field with AngularJS
Posted By : Arun Kumar | 31-Dec-2014
Focussing element with javascript can be done by just one line.
document.getElementById("myAnchor").focus();
But we are not supposed to write DOM manipulations code inside controllers of the respective page, Because controllers are meant to act as middle man between modal and view and thats it.
So,rather writing DOM manipulations inside controllers we can make a directive for that and use that directive on the element we are targetting.
Here's the code to do it.
Directive :
angular.module('application').directive('focus', function($timeout, $parse) {
return {
link: function(scope, element, attrs) {
var model = $parse(attrs.focus);
scope.$watch(model, function(value) {
if(value === true) {
$timeout(function() {
element[0].focus();
});
}
});
}
};
});
and the html
<input class="form-control" focus="true" type="text" placeholder="Placeholder"/>
Notice that focus directive we are using here and assigning "true" value to it.
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Arun Kumar
Arun is a creative UI Developer