Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

html - HTML5: How to set focus on a text input in a list with 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>

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    });
  }
});

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...