DOM manipulation should be in a directive instead of the controller. I would define a focusInput
directive and use it on the button:
<div class="button" focus-input>{{element.name}}</div>
Directive:
app.directive('focusInput', function($timeout) {
return {
link: function(scope, element, attrs) {
element.bind('click', function() {
$timeout(function() {
element.parent().parent().find('input')[0].focus();
});
});
}
};
});
Since jqLite is rather limited in terms of DOM traversal methods, I had to use parent().parent()
. You may wish to use jQuery or some JavaScript methods.
As you already found out, $timeout
is needed so that the focus()
method is called after the browser renders (i.e., finishes handling the click event).
find('input')[0]
gives us access to the DOM element, allowing us to use the JavaScript focus()
method (rather than find('input').focus()
which would require jQuery).