我使用AngularJS和ng-repeat指令将一个对象数组显示为一个列表.
<li ng-repeat="cue in cues" class="form-inline">
<input type="text" ng-model="cues[$index].text" class="input-xlarge"/>
{{cue.isNewest}}
</li>
属性“isNewest”仅在数组的一个元素上为true.我想将键盘焦点设置在该项目的文本输入上.我怎么能用AngularJS做到这一点?
解决方法
这是另一个使用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进行比较.
HTML:
<input type="text" ng-model="cues[$index].text" focus="{{cue.isNewest}}"
class="input-xlarge" />{{cue.isNewest}}
此fiddle还有一种方法可以切换数组中的哪个项应该具有焦点.
注意,如果你不加载jQuery,我们需要在link函数中使用element [0] .focus()(而不是element.focus())因为jqLite没有focus()方法.