在AngularJS中,“Angular的方法”是什么?

更具体的要求:

当打开一个模态时,将焦点设置在这个模态内预定义的<input>上。 每次<input>变得可见时(例如,通过单击某个按钮),将焦点设置在它上。

我尝试用自动对焦来实现第一个要求,但这只在Modal第一次打开时有效,并且只在某些浏览器中有效(例如在Firefox中它不起作用)。


当前回答

下面的指令对我来说很管用。对输入使用相同的autofocus html属性。

.directive('autofocus', [function () {
    return {
        require : 'ngModel',
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.focus();
        }
    };
}])

其他回答

首先,关注1.1的路线图是一种正式的方式。同时,您可以编写一个指令来实现设置焦点。

其次,在一个项目变得可见之后设置焦点,目前需要一个变通方法。只是用$timeout延迟对元素focus()的调用。

因为同样的控制器-修改- dom问题存在于焦点,模糊和选择,我建议有一个ng-target指令:

<input type="text" x-ng-model="form.color" x-ng-target="form.colorTarget">
<button class="btn" x-ng-click="form.colorTarget.focus()">do focus</button>

Angular线程在这里:http://goo.gl/ipsx4,更多细节在这里:http://goo.gl/4rdZa

下面的指令将在你的控制器中创建一个由ng-target属性指定的.focus()函数。(它也创建了.blur()和.select()。)演示:http://jsfiddle.net/bseib/WUcQX/

对于那些使用Bootstrap插件的Angular用户:

http://angular-ui.github.io/bootstrap/#/modal

你可以挂钩到模态实例的开放承诺:

modalInstance.opened.then(function() {
        $timeout(function() {
            angular.element('#title_input').trigger('focus');
        });
    });

modalInstance.result.then(function ( etc...

我发现其他一些答案过于复杂,而你真正需要的只是这个

app.directive('autoFocus', function($timeout) {
    return {
        restrict: 'AC',
        link: function(_scope, _element) {
            $timeout(function(){
                _element[0].focus();
            }, 0);
        }
    };
});

使用

<input name="theInput" auto-focus>

我们使用超时来让dom中的东西呈现,即使它是零,它至少会等待它-这种方式也适用于模态和其他东西

一个简单的情态动词:

.directive('focusMeNow', ['$timeout', function ($timeout)
{
    return {
        restrict: 'A',

        link: function (scope, element, attrs)
        {


            $timeout(function ()
            {
                element[0].focus();
            });



        }
    };
}])

例子

<input ng-model="your.value" focus-me-now />

这里只是一个新手,但我能够让它在ui.bootstrap.modal中工作,使用这个指令:

directives.directive('focus', function($timeout) {
    return {
        link : function(scope, element) {
            scope.$watch('idToFocus', function(value) {
                if (value === element[0].id) {
                    $timeout(function() {
                        element[0].focus();
                    });
                }
            });
        }
    };
});

在$modal中。我使用下面的方法来指示焦点应该放在哪里的元素:

var d = $modal.open({
        controller : function($scope, $modalInstance) {
            ...
            $scope.idToFocus = "cancelaAteste";
    }
        ...
    });

在模板上我有这个:

<input id="myInputId" focus />