HTML5:如何将焦点设置文本输入与AngularJS名单 [英] HTML5: How to set focus on a text input in a list with AngularJS

查看:143
本文介绍了HTML5:如何将焦点设置文本输入与AngularJS名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用AngularJS的NG-重复指令,以显示对象的数组列表。

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另一个指令执行$观察:

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 是相对于字符串真正的,而不是关键字真正

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}}

小提琴也有切换该数组中的项目应具有焦点的方法。

This fiddle also has a method to toggle which item in the array should have the focus.

请注意,如果你不加载jQuery的,我们需要在链接功能使用元素[0]。重点()(不是元素。重点())becaues jqLit​​e不具有焦点()方法。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆