AngularJs:手动将焦点设置为输入文本

时间:2016-02-24 12:51:30

标签: javascript angularjs focus

我需要手动设置焦点在输入元素上。我正在使用$event.currentTarget.focus();,但我不知道它为什么不起作用。这就是我在做的事情:

HTML:

<div ng-repeat="item in items track by $index" ng-dblclick="onDblClick($event,item)">
      <input type="text" ng-model="item.id" ng-disabled="!item.editing" ng-blur="onBlur(item)">
    </div>

脚本:

$scope.onDblClick = function($event, item) {
      item.editing = true;
      //setting the focus to elemnt but don't know why it's not working
      $event.currentTarget.focus();
    };

这是plunkr

1 个答案:

答案 0 :(得分:0)

无论如何,我自己想通了。我创建了一个指令focus并设置了$watch

<强> HTML:

<div ng-repeat="item in items track by $index" ng-dblclick="onDblClick($event,item)">
      <input type="text" ng-model="item.id" ng-disabled="!item.editing" ng-blur="onBlur(item)" focus="item.editing">
    </div>

<强>脚本:

app.directive('focus', function($timeout) {
    return function(scope, elem, attrs) {
      console.log(attrs)
      scope.$watch(attrs.focus, function(newval) {
        if (newval) {
          $timeout(function() {
            elem[0].focus();
          }, 0, false);
        }
      });
    };
  });

这是plunkr