为什么这只在第一次显示对话框时有效?

时间:2014-06-16 11:59:49

标签: angularjs twitter-bootstrap

使用带有此属性的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()">&times;
        </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>

第一次焦点移动到关闭按钮没问题。之后焦点停留在原来的位置。

我试图处理重复启动此错误对话框的回车键按键,我真的需要将焦点从对话框下方移开。

2 个答案:

答案 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);
              }
            }
        }
    };
});