如何將焦點設置在輸入字段上?在AngularJS中,聚焦于輸入場的“角度方式”是什么?更具體的要求:當模態,則將焦點設置為預定義的<input>在這個模態里面。每次<input>變得可見(例如,通過單擊某個按鈕),將焦點設置在上面。我試圖達到第一個要求帶著autofocus,但這只在第一次打開Modal時才起作用,而且只在某些瀏覽器中才起作用(例如,在Firefox中,它不起作用)。任何幫助都將不勝感激。
3 回答

桃花長相依
TA貢獻1860條經驗 獲得超8個贊
打開一個Modal時,將焦點設置在此Modal內預定義的<Input>上。
Name: <input type="text" focus-me="shouldBeOpen">
app.directive('focusMe', ['$timeout', '$parse', 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)); }); } };}]);
“2”每當<Input>變為可見時(例如,通過單擊某個按鈕),請將焦點設置在它上。
element[0].focus()
<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>
app.directive('focusMe', function($timeout) { return { link: function(scope, element, attrs) { scope.$watch(attrs.focusMe, function(value) { if(value === true) { console.log('value=',value); //$timeout(function() { element[0].focus(); scope[attrs.focusMe] = false; //}); } }); } };});
更新7/2013
Name: <input type="text" focus-me="{{shouldBeOpen}}">
app.directive('focusMe', function($timeout) { return { scope: { trigger: '@focusMe' }, link: function(scope, element) { scope.$watch('trigger', function(value) { if(value === "true") { $timeout(function() { element[0].focus(); }); } }); } };});
<button class="btn" ng-click="showForm=true; focusInput=true">show form and focus input</button><div ng-show="showForm"> <input type="text" focus-me="focusInput"> <button class="btn" ng-click="showForm=false">hide form</button></div>
app.directive('focusMe', function($timeout) { return { scope: { trigger: '=focusMe' }, link: function(scope, element) { scope.$watch('trigger', function(value) { if(value === true) { //console.log('trigger',value); //$timeout(function() { element[0].focus(); scope.trigger = false; //}); } }); } };});
- 3 回答
- 0 關注
- 741 瀏覽
添加回答
舉報
0/150
提交
取消