HTML5:如何使用 AngularJS 将焦点设置在列表中的文本输入上 [英] HTML5: How to set focus on a text input in a list with AngularJS
问题描述
我使用带有 ng-repeat 指令的 AngularJS 将对象数组显示为列表.
I use AngularJS with the ng-repeat directive to show an array of objects as a list.
<li ng-repeat="cue in cues" class="form-inline">
<input type="text" ng-model="cues[$index].text" class="input-xlarge"/>
{{cue.isNewest}}
</li>
属性isNewest"仅在数组的一个元素上为真.我想将键盘焦点设置在该项目的文本输入上.我怎样才能用 AngularJS 做到这一点?
The property "isNewest" is true on only one element of the array. I would like to set the keyboard focus on the text input of that item. How can I do that with AngularJS?
推荐答案
这是另一个使用 attrs.$observe 的指令实现:
Here is another directive implementation that uses attrs.$observe:
myApp.directive('focus', function () {
return function (scope, element, attrs) {
attrs.$observe('focus', function (newValue) {
newValue === 'true' && element[0].focus();
// or, if you don't like side effects (see @Christophe's comment):
//if(newValue === 'true') element[0].focus();
});
}
});
请注意,插入的 DOM 属性值(即 {{cue.isNewest}}
)始终计算为字符串,因此将 newvalue
与字符串进行比较的原因'true'
而不是关键字 true
.
Note that an interpolated DOM attribute value (i.e., {{cue.isNewest}}
) always evaluates to a string, hence the reason newvalue
is compared to the string 'true'
rather than keyword true
.
HTML:
<input type="text" ng-model="cues[$index].text" focus="{{cue.isNewest}}"
class="input-xlarge" />{{cue.isNewest}}
这个 fiddle 也有一个方法来切换数组中的哪个项目应该具有焦点.
This fiddle also has a method to toggle which item in the array should have the focus.
注意,如果不加载jQuery,我们需要在链接函数中使用element[0].focus()
(不是element.focus()
)因为 jqLite 没有 focus() 方法.
Note that if you do not load jQuery, we need to use element[0].focus()
in the link function (not element.focus()
) becaues jqLite doesn't have a focus() method.
这篇关于HTML5:如何使用 AngularJS 将焦点设置在列表中的文本输入上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!