Javascript 如何在ng repeat生成的下一个输入字段上设置焦点?
我有一个使用angularJS和ionic的iOS应用程序。当按下“返回”按钮时,我试图将键盘焦点转到下一个输入字段。以下是ng repeat存在的HTML代码:Javascript 如何在ng repeat生成的下一个输入字段上设置焦点?,javascript,html,ios,angularjs,Javascript,Html,Ios,Angularjs,我有一个使用angularJS和ionic的iOS应用程序。当按下“返回”按钮时,我试图将键盘焦点转到下一个输入字段。以下是ng repeat存在的HTML代码: <div class="row item-list" ng-repeat="item in shoppingList"> <div class="col col-10 col-check" ng-click="checkItem($index)">
<div class="row item-list" ng-repeat="item in shoppingList">
<div class="col col-10 col-check" ng-click="checkItem($index)">
<i class="icon ion-checkmark-round" ng-if="item.Action == 'check'"></i>
</div>
<div class="col col-memo" ng-click="updateMemo($index)">
<label class="item-list item-input">
<input id="inputText" type="text" placeholder="" ng-model="item.EventContent" on-return="nextLine($index)"/>
</label>
</div>
</div>
在我的控制器中调用我的nextLine函数:
myScope.nextLine = function (index) {
//get next html input element and .setFocus()
}
其中index是当前输入框索引。我需要一种方法来获取下一个HTML输入元素并在那里设置焦点。非常感谢您的帮助。根据我的经验,更为事件驱动的方法更适合焦点管理。将事件传递给nextLine方法。假设您只使用jQuery light,那么最终会得到如下结果:
//add closest method to jQuery light
$.fn.closest = function (selector) {
var el = this[0];
while (el && self.matches(el, selector)) {
el = el.parentElement;
}
return $(el);
};
myScope.nextLine = function (event) {
var nextInput = $(event.target).closest("[ng-repeat]").find("input");
if(nextInput[0]){
nextInput[0].focus();
}
}
首先,不建议在DOM事件侦听器中使用多个指令实例。如果有1000条指令侦听同一个“keydown”事件,会怎么样?那太疯狂了 也许您应该使用好的'ol Jquery:添加一个 将“keydown”事件侦听器发送到容器元素,然后在按下每个“return”键的情况下在输入字段上迭代: 模板的简化版本:
<div class="items-lists" on-return>
<input type="text" ng-repeat="item in shoppingList" class="item-list">
</div>
angular.module('MyApp')
.directive('onReturn', function() {
return {
restrict: 'A',
link: function(scope, element, attr) {
$(element).on("keydown keypress", function(event) {
if (event.which === 13) {
scope.nextLine();
event.preventDefault();
}
});
//get next html input element and set focus()
scope.nextLine = function() {
var nextInput = $(element).find('input:focus').next('input');
var firstInput = $(element).find('input')[0];
nextInput.length ? nextInput.focus() : firstInput.focus();
}
}
}
});
解决方案#2:
另一种方法是使用接受布尔表达式的ng focus
。您可以为ng repeat
中的每个项目创建一个ng click函数,将其设置为“selected”,并取消选择其余项目。然后评估项。在输入字段中选择,以获得焦点:
<div class="items-lists">
<input ng-repeat="item in shoppingList" ng-focus="item.selected" ng-click="selectItem(item)" class="item-list">
</div>
不要使用范围。$apply
直接使用,而是使用$timeout()
-它对$apply的使用是“聪明的”
-而不是“残忍的”。
<div class="items-lists">
<input ng-repeat="item in shoppingList" ng-focus="item.selected" ng-click="selectItem(item)" class="item-list">
</div>