本文转自:http://stackoverflow.com/questions/14833326/how-to-set-focus-on-input-field,未作修改。
What is the 'Angular way' to set focus on input field in AngularJS?
More specific requirements:
- When aModalis opened,set focus on a predefined
<input>
inside this Modal. - Everytime
<input>
becomes visible (e.g. by clicking some button),set focus on it.
I tried to achieve the first requirementwithautofocus
,but this works only when the Modal is opened for the first time,and only in certain browsers (e.g. in Firefox it doesn't work).
Any help will be appreciated.
375
@L_301_5@
|
Define a directive and have it $watch a property/trigger so it knows when to focus the element: Name: <input type="text" focus-me="shouldBeOpen">
app.directive('focusMe',function($timeout,$parse) { return { //scope: true,// optionally create a child scope link: function(scope,element,attrs) { var model = $parse(attrs.focusMe); scope.$watch(model,function(value) { console.log('value=',value); if(value === true) { $timeout(function() { element[0].focus(); }); } }); // to address @blesh's comment,set attribute value to 'false' // on blur event: element.bind('blur',function() { console.log('blur'); scope.$apply(model.assign(scope,false)); }); } }; }); The $timeout seems to be needed to give the modal time to render.
Create a directive essentially like the one above. Watch some scope property,and when it becomes true (set it in your ng-click handler),execute <button class="btn" ng-click="showForm=true; focusInput=true">show form and focus input</button> <div ng-show="showForm"> <input type="text" ng-model="myInput" focus-me="focusInput"> {{ myInput }} <button class="btn" ng-click="showForm=false">hide form</button> </div>
Plunker |