Create a directive for autofocus and use where ever you need on the module.
I have explained the same using Angular 2/5 concept as well, for that please check this link:- Angular autofocus for input box - Angular 2/5.
Directive
// Common directive for Focus
angular.module('sampleapp').directive('focus',
function($timeout) {
return {
scope : {
trigger : '@focus'
},
link : function(scope, element) {
scope.$watch('trigger', function(value) {
if (value === "true") {
$timeout(function() {
element[0].focus();
});
}
});
}
};
});
View
Auto Focus : <input type="text" focus="true">
Related Posts
1. Angular ng-repeate in directive
3. Filtering concept in angular js
5. Simple client side sorting in angular
Thanks! works like a charm
ReplyDeleteThanks. I tweaked your example to help me solve my problem.
ReplyDeleteThank you for this! Very helpful!
ReplyDeleteThx for very simple solution
ReplyDeleteThis doesn't seem to work when focus takes the value of a scope variable. Fiddle - http://jsfiddle.net/0qq8ntsp/
ReplyDeleteSorry, this is the correct Fiddle - http://jsfiddle.net/au51zjux/3/
ReplyDeleteHow did you fix that? I am having the same problem. I cannot bind a variable to set focus or not.
DeleteReally sorry! Ignore my last two comments.
ReplyDeleteWorks great. Thank you.
ReplyDeleteWorks for me. Thanx
ReplyDeleteWhy you have to create new directive for doing this while
ReplyDeleteangularjs alreay has a built in method for this situation, just use ng-focus="true".
^ This directive is for auto-focusing when a page loads as well.
ReplyDeleteyes
Deletethank you, this worked perfectly for me
ReplyDeleteWhy $timeout is used?
ReplyDeleteInstead of $apply I used $timeout which is better than $apply.
Deletethanks, using trigger : '=focus' things get much better
ReplyDeletefriend can you give me a directive to restrict autofill data in textbox(autocomplete==off doesn't support)
ReplyDeleteAwesome!!
ReplyDeleteThanks! Works great!
ReplyDeleteNice work thank you very much!
ReplyDeleteThank you for your help.
ReplyDeleteIt works very well.
awesome!!!!!!!!! :)
For some reason, I copied this code (only replaced the app name) and it does not work with modal windows. I tried renaming the focus to focusOnMe (focus-on-me in html) and it still did not work. I put in JS timeout to focus by id as a workaround (when the modal window is ready for events), but I can't figure out why it is not triggering.
ReplyDeleteThank you. This directive helped me a lot :)
ReplyDelete