我的任务
使用最大字符数创建3个输入。长度5进入第5个字符时。在输入中,光标应在插入char后立即跳转到下一个输入。删除输入的第一个字符时,光标应该在删除该字符后立即跳到上一个输入的末尾。
我做了什么
创建了3个输入字段,并使用监视组将字符长度限制为5,并且它正常运行
我的问题
当输入字段达到最大字符长度5时,如果第一个字符已从输入字段中删除,我需要将光标移动到下一个输入字段,光标应自动移动到前一个输入字段结束
我的plunker链接在https://plnkr.co/edit/Bcq6slz9gbK8r6Lm8MAh?p=preview
我的角度代码
var app = angular.module("task8", []);
app.controller("taskController8",["$scope", function ($scope) {
$scope.charLength=5
$scope.$watchGroup(['firstInput', 'secondInput', 'thirdInput'], function (newValue, oldValue) {
if (newValue) {
if (newValue[0].length > 5) {
$scope.firstInput = oldValue[0];
}
else if (newValue[1].length > 5) {
$scope.secondInput = oldValue[1];
newValue[2].focus();
}
else if (newValue[2].length > 5) {
$scope.thirdInput = oldValue[2];
}
$scope.charLength = 5 - newValue[0].length;
$scope.charLength = 5 - newValue[1].length;
$scope.charLength = 5 - newValue[2].length;
}
})
$scope.updateBody = function (event) {
return false;
};
}]);
答案 0 :(得分:4)
以下是AngularJS Directive的一个工作示例:
angular
.module('MyApp', [])
.directive('moveFocus', function() {
function getCaretPosition(elem) {
// Internet Explorer Caret Position
if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
var bookmark = range.getBookmark();
return bookmark.charCodeAt(2) - 2;
}
// Firefox Caret Position
return elem.setSelectionRange && elem.selectionStart;
}
return {
restrict: 'A',
link: function(scope, elem, attr) {
var tabindex = parseInt(attr.tabindex);
var maxlength = parseInt(attr.maxlength);
elem.on('input, keydown', function(e) {
var val = elem.val(),
cp,
code = e.which || e.keyCode;
if (val.length === maxlength && [8, 37, 38, 39, 40, 46].indexOf(code) === -1) {
var next = document.querySelectorAll('#input' + (tabindex + 1));
next.length && next[0].focus();
return;
}
cp = getCaretPosition(this);
if ((cp === 0 && code === 46) || (cp === 1 && code === 8)) {
var prev = document.querySelectorAll('#input' + (tabindex - 1));
e.preventDefault();
elem.val(val.substring(1));
prev.length && prev[0].focus();
return;
}
});
}
};
});
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
<form name="form">
<div class="form-group">
<label for="input1">Input 1</label>
<input type="text" class="form-control" id="input1" name="input1" tabindex="1" maxlength="5" move-focus placeholder="Input 1">
</div>
<div class="form-group">
<label for="input2">Input 2</label>
<input type="text" class="form-control" id="input2" name="input2" tabindex="2" maxlength="5" move-focus placeholder="Input 2">
</div>
<div class="form-group">
<label for="input3">Input 3</label>
<input type="text" class="form-control" id="input3" name="input3" tabindex="3" maxlength="5" move-focus placeholder="Input 3">
</div>
</form>
</div>