I use AngularJS with the ng-repeat directive to show an array of objects as a list.
<li ng-repeat="cue in cues" class="form-inline">
<input type="text" ng-model="cues[$index].text" class="input-xlarge"/>
{{cue.isNewest}}
</li>
The property "isNewest" is true on only one element of the array. I would like to set the keyboard focus on the text input of that item. How can I do that with AngularJS?
Here is another directive implementation that uses attrs.$observe:
Note that an interpolated DOM attribute value (i.e.,
{{cue.isNewest}}
) always evaluates to a string, hence the reasonnewvalue
is compared to the string'true'
rather than keywordtrue
.HTML:
This fiddle also has a method to toggle which item in the array should have the focus.
Note that if you do not load jQuery, we need to use
element[0].focus()
in the link function (notelement.focus()
) becaues jqLite doesn't have a focus() method.The other proposed answers work OK 9/10 times for me, but soon I was running in "$digest already in progress" fun.
I have a slightly modified version of the previous answers by asgoth and Mark Rajcok. Basically you inject the $timeout dependency and put the focus() call inside of a timeout(...). IIRC ng-focus does the same.
There is no special feature in AngularJS to receive focus. You could solve this with a $watch in your controller, but also with a directive.
Since you would be manipulating the DOM, you will need to create a directive. Something like:
Html:
Note: untested.