简体   繁体   English

Angular - 将焦点放在动态创建的输入字段上

[英]Angular - Give focus to a dynamically created input field

How would I add focus to the newly created field? 如何将焦点添加到新创建的字段? See example thus far: http://jsfiddle.net/aERwc/165/ 见到目前为止的例子: http//jsfiddle.net/aERwc/165/

$scope.addField = function() {console.log('hi');
    $scope.fields[$scope.keyToAdd] = $scope.valueToAdd;
    $scope.setFieldKeys();
    $scope.keyToAdd = '';
    $scope.valueToAdd = '';
}

You can use this approach however it will require to add animation to your ng-repeat. 您可以使用此方法,但需要在ng-repeat中添加动画。 see ng-repeat animation complete callback 看看ng-repeat动画完成回调

Basically in callback call element.focus() 基本上在回调中调用element.focus()

.animation('.repeat-animate', function () {
  return {
    enter: function (element, done) {
      element.hide().show(100, function(){
        var scope = element.scope();
        scope.$evalAsync(function(){ 
          element.find(':last')[0].focus();
        }); 
      });
    }
  };
});

UPDATED CODEPEN: http://codepen.io/ev-tt/pen/BNXBmd?editors=101 更新的CODEPEN: http ://codepen.io/ev-tt/pen/BNXBmd?编辑= 101

To me, this seems like the simplest way to do it: 对我来说,这似乎是最简单的方法:

Code Pen 密码笔

HTML HTML

<html ng-app='app'>
  <body ng-controller='MainController as vm'>
    <input ng-repeat='thing in vm.things'>
    <hr />
    <button ng-click='vm.addThing()'>Add Thing</button>
  </body>
</html>

JS JS

angular
  .module('app', [])
  .controller('MainController', MainController)
;

function MainController($timeout) {
  var vm = this;
  vm.things = [{}];
  vm.addThing = function() {
    vm.things.push({});
    $timeout(function() {
      // have to do this in a $timemout because
      // we want it to happen after the view is updated
      // with the newly added input
      angular
        .element(document.querySelectorAll('input'))
        .eq(-1)[0]
        .focus()
      ;
    }, 0);
  };
}

Personally, I would actually use jQuery and make the code even simpler: 就个人而言,我实际上会使用jQuery并使代码更简单:

$('input:last').focus();

Instead of: 代替:

angular
  .element(document.querySelectorAll('input'))
  .eq(-1)[0]
  .focus()
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM