我需要根据需要验证一些输入字符,当输入所有输入字符时,我将进行ajax调用以验证它们的组合在服务器上是否正确。
我遇到的问题是,我需要在用户输入字符后立即将焦点移至下一个输入。
我可以使用jQuery或Javascript轻松完成此操作,但我需要使用AngularJs,以正确的方式使用AngularJ"。
到目前为止我尝试的东西如下。
我的HTML
var myApp = angular.module("myApp", []);
myApp.controller("myController", ["$scope", function myController($scope) {
$scope.verify = function verify() {
//here I would have my code to verify the combination of characters entered by the user
};
}]);
myApp.directive("moveToNext", function () {
return {
restrict: 'A',
require: ['ngModel'],
link: function (scope, element, attrs, ctrls) {
element.bind("keydown keypress", function (event) {
if (element[0].value.trim().length > 0) {
}
});
}
};
});

.code-character {
width:25px;
margin-right: 5px;
border: solid lightgrey 2px;
text-align:center;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<table ng-app="myApp" ng-controller="myController">
<tr>
<td>
<input type="text" class="code-character" maxlength="1" ng-model="firstCharacter" name="firstCharacter" required autofocus move-to-next="verify()" />
</td>
<td>
<input type="text" class="code-character" maxlength="1" ng-model="secondCharacter" name="secondCharacter" required autofocus move-to-next="verify()" />
</td>
<td>
<input type="text" class="code-character" maxlength="1" ng-model="thirdCharacter" name="thirdCharacter" required autofocus move-to-next="verify()" />
</td>
<td>
<input type="text" class="code-character" maxlength="1" ng-model="fourthCharacter" name="fourthCharacter" required autofocus move-to-next="verify()" />
</td>
<td>
<input type="text" class="code-character" maxlength="1" ng-model="fifthCharacter" name="fifthCharacter" required autofocus move-to-next="verify()" />
</td>
<td>
<input type="text" class="code-character" maxlength="1" ng-model="sixthCharacter" name="sixthCharacter" required autofocus move-to-next="verify()" />
</td>
</tr>
</table>
&#13;
一旦有了一些价值,我如何找到并关注下一个元素?
答案 0 :(得分:1)
你可以用jquery
找到下一个空输入element.bind("keydown keypress", function (event) {
if (element[0].value.trim().length > 0) {
$(element).closest('tr').find('input').each(function(){
if($(this).val().length === 0){
$(this).focus();
return false;
}
})
}
});