gpt4 book ai didi

angularjs - 访问 ng-repeat 中嵌套的下一个/上一个输入的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-03 04:34:20 25 4
gpt4 key购买 nike

我将 keyup 绑定(bind)添加到嵌套在 ng-repeats 中的输入,以便顺利地从下一个输入到上一个输入,类似于 this question 。不同之处在于,解决方案适用于直接相邻 sibling 的输入。

这是我的 html 的原型(prototype):

<div ng-repeat="student in students" >
<div class="input-append">
<input class="span3" type="text" ng-model="student.name"
ng-required="student.name.split(' ').length>1" focus-others index="{{ $index }}" focus="{{ focus.value }}"/>
<button class="btn btn-danger" type="button" ng-click="deleteInput($index)">X</button>
</div>
</div>

我目前有两种都有效的解决方案。

<小时/>

第一个解决方案 - 遍历 dom 寻找输入,匹配聚焦的输入,然后在 keyup 上聚焦下一个输入:

app.directive('focusOthers', function($timeout){
return function(scope, element){
var inputs;
$timeout(function(){
inputs = document.querySelectorAll('input[type="text"]');
},0)
element.bind('keyup', function(e){
var current = document.activeElement;
if (e.keyCode == 13){
event.preventDefault();
var i = 0;
while( i<inputs.length){
if (inputs[i]==current){
var nextInput = inputs[i+1];
nextInput.focus();
i=inputs.length;
}
i++;
}
}
})
}
});

Here's a working plunk

<小时/>

第二个解决方案 - 这是一个更加“有 Angular ”的解决方案,因为指令处理元素属性内的信息以确定哪个元素获得焦点。

app.directive('focusOthers', function(){
return {
link: function(scope, element, attrs){
// scope.index = attrs.index - wouldn't it be nice if this worked?
attrs.$observe('index', function(val){
scope.index = parseInt(val);
});
attrs.$observe('focus', function(val){
if(scope.focus.value == scope.index){
element[0].focus();
}
});

element.bind('keyup', function(e){
if(e.keyCode==13){
scope.focus.value = scope.index + 1;
scope.$apply();
}
});
}
}
});

Here's the plunk对于这个方法。

每个可能的缺点:

第一种方法是纯dom遍历。我不一定对此有问题,但每次你遍历 dom 并使用 $timeout 来等待渲染时,就会有人大喊“这不是 Angular 的设计目的。”

--我猜第二种方法更“有 Angular ”,但是该指令在属性上注册了 $observe ,并且页面上可能有 400+ 个输入,我不知道这是否会影响性能.

所以我的问题是,是否有更好的方法来访问这些嵌套输入,既可以安抚 Angular 之神,又可以在浏览器上轻松浏览?或者我的方法之一是更好的方法吗?或者我应该放弃并在 Python/Jinja2 中完成这一切;) ?

最佳答案

我认为更令浏览器/用户满意的方法是使用 tabindex 属性。您可以在每个输入元素上吐出此属性,并使用 $index 值来获取 ng-repeat 所在的迭代次数。许多浏览器和移动设备都连接到此属性,以提供通过表单和列表的导航(例如,当聚焦于表单输入时,iOS 中的前进/后退箭头)

另一种解决方案是每个元素使用一个指令

<input focus-this="{{$index}}"></input>

然后

directives.directive('focusThis', function(){
return {
link: function (scope, element, attrs){
scope.$watch('focusedIndex', function(newVal, oldVal){
if (newVal == attrs['focus-this']){
element.focus();
}
else {
element.blur();
}
});
}
};
});

您应该能够使用 keydown 事件更改 FocusedIndex 以转到上一个/下一个,甚至根据需要跳转到特定索引。

警告:未经测试的代码。只是一个概念。可能需要调整。

关于angularjs - 访问 ng-repeat 中嵌套的下一个/上一个输入的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17530216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com