Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 角度:当窗体显示时,如何使输入元素聚焦?_Angularjs_Angularjs Directive - Fatal编程技术网

Angularjs 角度:当窗体显示时,如何使输入元素聚焦?

Angularjs 角度:当窗体显示时,如何使输入元素聚焦?,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我希望在我的表单中的某个特定输入上给予关注,当我赋予它可见性时(ng show value变为true)。 为此,我写了一份指令: angular.module('ui.directives', []).directive('autoFocus', function ($timeout) { return { scope: { trigger: '@autoFocus' },

我希望在我的表单中的某个特定输入上给予关注,当我赋予它可见性时(ng show value变为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中都不起作用

这是一个很好的例子来说明我的意思

我想问题是指令在页面加载时运行…

如何在ng show上实现它?(很抱歉,angular…:-()

您的
自动对焦
属性的值(
触发器
在指令内)应该与
显示
变量具有相同的值,因为您希望在
显示
的值更改时发生某些事情:

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" />
angular.module('ui.directives',[]).directive('autoFocus',
函数($timeout){
返回{
范围:{
触发器:'=自动对焦'
},
链接:功能(范围、元素){
范围:$watch('trigger',
函数(值){
如果(值){
$timeout(函数(){
console.log('autoFocus:通过id为元素提供焦点:',元素[0].id);
元素[0]。焦点();
});
}
});
}
};
});

工作提琴:

谢谢!但不幸的是,它不工作,对我来说…:-((当显示表单时,输入“b”没有焦点…,使用FF和Chrome进行测试…。问题可能是指令在页面加载时运行,而不是在sow值更改时…(我只在页面加载时看到控制台日志消息…).jsFiddle似乎丢失了我的更改。请尝试更新的链接。请注意,我的答案中的代码与正在工作的jsFddle代码相同。因此,请使用上面发布的代码。完美。立即工作。我在触发器的值中遗漏了“=自动聚焦…”…:-)