Focus on an input element by default on angular form load

9,218 views
Skip to first unread message

Ankit Dhingra

unread,
Aug 28, 2012, 1:22:34 AM8/28/12
to ang...@googlegroups.com
I was trying to search for a way in which I can put the focus on a single form input element inside the html form.
There is the ofcourse the jquery way to do it on document ready, however
I was hoping that angularjs would have some directive for the same.

Regards,
Ankit.

Toshihide Shimayama

unread,
Aug 28, 2012, 4:08:33 AM8/28/12
to ang...@googlegroups.com
Have you tried html5 form autofocus attribute?
<input ng-model="text" autofocus/>

--tosh

Ankit Dhingra

unread,
Aug 29, 2012, 11:52:08 AM8/29/12
to ang...@googlegroups.com
Exactly what I was looking for! Thanks :)

Thilagavathy R

unread,
Sep 12, 2013, 10:45:53 AM9/12/13
to ang...@googlegroups.com

Thanks. it saved my time :)

Luke Kende

unread,
Sep 14, 2013, 2:03:53 AM9/14/13
to ang...@googlegroups.com
That's great for html5 browsers.  But what about when you want to select an input's text and that text doesn't get added until after an ajax call?  Here's a directive I created as one approach:

.directive('selectOnPageLoad',function($timeout){
return {
link: function(scope,element){
//wait until intial value is there, then select it, then clear the watch so doesn't keep doing it
var clearWatch = scope.$watch(
function(){ return $(element[0]).val(); },
function(value){
if (value){
element[0].select();
clearWatch();
}
}
)
}
}
})

Daniel Wolf

unread,
Mar 2, 2014, 12:52:22 PM3/2/14
to ang...@googlegroups.com
@Luke, this works great but no need for the dependence on jQuery

replaced $(element[0]).val(); with element[0].value.
Reply all
Reply to author
Forward
0 new messages