使用带有此属性的ui-bootstrap附加到对话框上的ok / save按钮。 第一次创建对话框时,它会按预期关注按钮。 以后每次都没有效果。
.directive('autoFocus', function($timeout) {
return {
restrict: 'AC',
link: function(_scope, _element) {
$timeout(function(){
_element[0].focus();
}, 0);
}
};
});
模态模板看起来像这样(这来自Michael Conroy的角对话服务):
<div class="modal" ng-enter="" id="errorModal" role="dialog" aria-Labelledby="errorModalLabel">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header dialog-header-error">
<button type="button" class="close" ng-click="close()">×
</button>
<h4 class="modal-title text-danger"><span class="glyphicon glyphicon-warning-sign"></span> Error</h4>
</div>
<div class="modal-body text-danger" ng-bind-html="msg"></div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" autoFocus ng-click="close()">Close</button>
</div>
</div>
</div>
</div>
第一次焦点移动到关闭按钮没问题。之后焦点停留在原来的位置。
我试图处理重复启动此错误对话框的回车键按键,我真的需要将焦点从对话框下方移开。
答案 0 :(得分:2)
事实证明,自动对焦是指令的一个非常糟糕的选择。我将其重命名为takefocus,现在它每次都可以正常工作而不会有任何变化。为什么自动对焦不起作用?甘拜下风。有角度和工作的覆盖指令和其他标签,但是使用指令覆盖自动聚焦不会。
答案 1 :(得分:1)
这是因为当元素添加到舞台时指令autoFocus被编译一次并且链接函数没有被再次调用,如果你在父作用域上有一个变量负责显示类似$scope.opened
的模态你可以在所述变量上使用$ watcher,即如果ith从false变为true set focus
.directive('autoFocus', function($timeout, $watch) {
return {
restrict: 'AC',
link: function(_scope, _element) {
$watch('_scope.opened', function (newValue) {
if(newValue){
$timeout(function(){
_element[0].focus();
}, 0);
}
}
}
};
});