首页 文章

Angular:如何在显示表单时将焦点放在input元素上?

提问于
浏览
0

当我给它提供可见性(ng-show值变为true)时,我想关注我表单中的特定输入 .
我为此目的写了一个指令:

angular.module('ui.directives', []).directive('autoFocus',
    function ($timeout) {
        return {
            scope: {
                trigger: '@autoFocus'
            },
            link: function (scope, element) {
                scope.$watch('trigger',

                function (value) {
                    if (value === 'true') {
                        $timeout(function () {
                            console.log('autoFocus: giving focus to element by id:', element[0].id);
                            element[0].focus();
                        });
                    }
                });
            }
        };
    }
);

这在Firefox和Chrome中都不起作用 .

这是jsfiddle来表明我的意思......

我想问题是指令是在页面加载上运行的...
如何在ng-show上执行它变成了现实? (抱歉,角度很新...... :-()

1 回答

  • 2

    您的 autoFocus 属性的值(指令内的 trigger )应该与 show 变量具有相同的值,因为您希望在 show 的值更改时发生某些事情:

    angular.module('ui.directives', []).directive('autoFocus',
    
    function ($timeout) {
        return {
            scope: {
                trigger: '=autoFocus'
            },
            link: function (scope, element) {
                scope.$watch('trigger',
    
                function (value) {
                    if (value) {
                        $timeout(function () {
                            console.log('autoFocus: giving focus to element by id:', element[0].id);
                            element[0].focus();
                        });
                    }
                });
            }
        };
    });
    
    <input type="text" id="b" value="B" auto-focus="show" />
    

    工作小提琴:http://jsfiddle.net/ex9d6oa4/

相关问题