专注于ng-repeat生成的输入 [英] Focus on input generated by ng-repeat

查看:75
本文介绍了专注于ng-repeat生成的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

html代码

  <div class="row" ng-repeat="form in data.forms track by $index">
            <form name="myForm">
                <input id="search_{{$index}}" type="text" name="location" ng-model="form.query" ng-keyup="keyUp($index)"  >
            </form>

   </div>

角度代码

 $scope.data = {
                            forms: []

                        };
        jQuery(document).ready(function() {
                                        setTimeout(function() {
                                            jQuery('#search_0').focus();
                                        }, 500);
                                    });

上面的代码有效,但是需要额外的setTimeout.有没有更好的方法等待表单生成然后执行focus()?

The above code works, but needs an extra setTimeout. Is there a better way to wait for the forms to be generated and then do focus()?

推荐答案

第一条Angular规则:不要在指令范围之外接触DOM.

First Rule of Angular: Do not touch the DOM outside of the scope of the directive.

ngRepeat中的第一个输入元素可以使用自定义指令集中,该指令将利用$first范围变量.指令%3angRepeat"rel =" nofollow> ngRepeat :

First input element inside the ngRepeat can be focused with custom directive which will make use of the $first scope variable provided automatically by ngRepeat:

PLUNKER

app.directive('focusedOn', [
    '$timeout'
    ,function($timeout) {
      return function($scope, $element, $attrs) {
        function focus(){
          $timeout(function(){
            $element.focus();
          }, 20);
        }

        if(_($attrs.focusedOn).isEmpty()){
          return focus();
        }

        $scope.$watch($attrs.focusedOn, function(newVal){
          if(newVal){
            focus();
          }
        });

      };

    }
  ]

);

<div class="row" ng-form="myForm" ng-repeat="form in forms track by $index">
  <input type="text" name="location" ng-model="form.query" focused-on="$first" />
</div>

注意:没有$ timeout,它可能会起作用,也可能不会起作用.

这篇关于专注于ng-repeat生成的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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