无法在Angular

时间:2015-08-12 10:13:48

标签: javascript angularjs

我有一个有角度的应用程序。在一个控制器内部,我有一个隐藏答案的字段。使用ng-click单击按钮时,将显示该字段。我想将光标聚焦在该字段中。我尝试过使用:

document.getElementById("answer").focus();

但这不起作用。但是,当提交答案时,会运行一些代码,然后document.getElementById("answer").focus();才能运行。

显示该字段的原始函数是:

$scope.startStream = function () {
  $scope.showStream = true;
  document.getElementById("answer").focus();
};

为什么不关注光标?

2 个答案:

答案 0 :(得分:1)

我理解这里的问题是“为什么它不关注光标”。

这是因为在整个函数执行后,模板由Angular处理。这是当拾取showStream并出现按钮时。当您调用document.getElementBy时,模板尚未处理且按钮不存在。

答案 1 :(得分:1)

您可以使用简单的指令,假设您要使用$scope.showStream

angular.module('app')
    .directive('focusOnMe', function () {
        return {
            scope: {
                showStream: '='
            },
            link: function ($scope, $element, $attrs) {
                $scope.$watch('showStream', function () {
                    if ($scope.showStream) {
                        $element[0].focus();
                    }
                });
            }
        };
    });

像这样使用:

<input type="text" ... focus-on-me="showStream" />