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

更具体的要求:

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

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


当前回答

不确定依赖超时是否是一个好主意,但这适用于ng-repeat,因为这段代码在angularjs更新DOM后运行,所以你要确保所有对象都在那里:

myApp.directive('onLastRepeat', [function () {
        return function (scope, element, attrs) {
            if (scope.$last) setTimeout(function () {
                scope.$emit('onRepeatLast', element, attrs);
            }, 1);
        };
    }]);
    //controller for grid
    myApp.controller('SimpleController', ['$scope', '$timeout', '$http', function ($scope, $timeout, $http)
    {
        var newItemRemoved = false;
        var requiredAlert = false;
        //this event fires up when angular updates the dom for the last item
        //it's observed, so here, we stop the progress bar
        $scope.$on('onRepeatLast', function (scope, element, attrs) {
            //$scope.complete();
            console.log('done done!');
            $("#txtFirstName").focus();
        });
    }]);

其他回答

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

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

使用

<input name="theInput" auto-focus>

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

HTML有一个属性autofocus。

<input type="text" name="fname" autofocus>

http://www.w3schools.com/tags/att_input_autofocus.asp

如果你想把焦点设置在特定的元素上,你可以使用下面的方法。

创建一个名为focus的服务。 angular.module(“应用程序”) .factory('focus', function ($timeout, $window) { 返回函数(id) $timeout(函数){ var element = $window.document.getElementById(id) 如果(元素) element.focus (); }); }; }); 将它注入到您希望调用的控制器中。 调用此服务。

这可能是ES6时代最简单的解决方案。

添加下面的一行指令使得HTML的“autofocus”属性在Angular.js上有效。

.directive('autofocus', ($timeout) => ({link: (_, e) => $timeout(() => e[0].focus())}))

现在,你可以使用HTML5自动对焦语法,比如:

<input type="text" autofocus>

我想在寻找一个更好的解决方案,但没有找到它,而是不得不创造它之后,为这个讨论做出贡献。

标准: 1. 解决方案应该独立于父控制器范围,以增加可重用性。 2. 避免使用$watch来监视某些条件,这既缓慢,又增加了摘要循环的大小,并且使测试更加困难。 3.避免$timeout或$scope.$apply()触发摘要循环。 4. input元素出现在使用Directive打开的元素中。

这是我最喜欢的解决方案:

指令:

.directive('focusInput', [ function () {
    return {
        scope: {},
        restrict: 'A',
        compile: function(elem, attr) {
            elem.bind('click', function() {
                elem.find('input').focus();                
            });
        }        
    };
}]);

Html:

 <div focus-input>
     <input/>
 </div>

我希望这篇文章能帮助到一些人!