使用angularjs将焦点更改为下一个输入文本 [英] change focus to the next input text with angularjs

查看:99
本文介绍了使用angularjs将焦点更改为下一个输入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有一个对象变量(var myObject),在IHM中分为3个输入文本.

I have an object variable in my controller (var myObject), divided into 3 input text in the IHM.

当焦点已达到maxLength时,我想自动将焦点更改为下一个输入.

I want to change automatically the focus to the next input when the focused one reached the maxLength.

var myObject = {
   part1:"",
   part2:"",
   part3:""
}



<form>
    <input type="text" id="part1" ng-model="myObject.part1" maxlength="7"/>
    <input type="text" id="part2" ng-model="myObject.part2" maxlength="12"/>
    <input type="text" id="part2" ng-model="myObject.part2" maxlength="12"/>
</form>

推荐答案

您需要为此使用指令:

app.directive("moveNextOnMaxlength", function() {
    return {
        restrict: "A",
        link: function($scope, element) {
            element.on("input", function(e) {
                if(element.val().length == element.attr("maxlength")) {
                    var $nextElement = element.next();
                    if($nextElement.length) {
                        $nextElement[0].focus();
                    }
                }
            });
        }
    }
});

并按如下所示更新您的表单:

And update your form as follows:

<form>
    <input type="text" id="part1" ng-model="myObject.part1" maxlength="7" move-next-on-maxlength />
    <input type="text" id="part2" ng-model="myObject.part2" maxlength="12" move-next-on-maxlength />
    <input type="text" id="part2" ng-model="myObject.part2" maxlength="12"/>
</form>

演示

可以将指令移至<form>元素上,但是build-int jqLit​​e的find()方法将限制您仅按标记名称查找元素.如果您使用的是完整的jQuery,或者可以改用vanillaJS,则建议使用此方法.

You could move the directive onto the <form> element instead, but the build-int jqLite's find() method will restrict you to only finding elements by tag name. If you're using full jQuery, or can use vanillaJS instead, I would suggest this method.

这篇关于使用angularjs将焦点更改为下一个输入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆