将文本区域集中在ng-click上

Focus textarea on ng-click

本文关键字:ng-click 集中 文本 区域      更新时间:2023-09-26

我想从ng-repeat中单击一个按钮,并从特定项目中关注textarea

<div ng-repeat="item in items">
  <textarea focus-when="showTextarea">{{ item }}</textarea>
  <a ng-click="trigger()" href="#">Focus</a>
</div>
Javascript

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.items = ['World', 'Earth', 'Fire'];
  $scope.trigger = function() {
    $scope.showTextarea = true;
  }
});
app.directive('focusWhen', function($scope) {
  return {
    link: function(scope, element, attrs) {
      scope.$watch(attrs.focusWhen, function(value) {
        console.log(attrs);
        element.css('background','red');
        console.log(element[0]);
        element[0].focus();
      });      
    }
  }
});

代码:http://plnkr.co/edit/By0hLs7U6CLbGD9ic9vO?p=preview

我有指令focusWhen,它监视showTextarea范围变量。当ng-click触发时,它会将showTextarea更改为true并且它应该聚焦textarea

然而,我的代码不工作,它有错误

Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- focusWhenDirective

我不知道为什么。两个问题:

  1. 你能帮我指出我错在哪里吗

  2. 点击后如何进行聚焦?

谢谢。

更新1

我使用

下面的代码使其工作

<div ng-controller="MyCtrl">
<div ng-repeat="item in items">
    <button class="btn" ng-click="showForm=true; focusInput=true">show form and focus input #{{ item }}</button>
    <div ng-show="showForm">
      <input type="text" focus-me="focusInput">
      <button class="btn" ng-click="showForm=false">hide form</button>
    </div>
  </div>
</div>
Javascript

var app = angular.module('plunker', []);
var MyCtrl = function ($scope, $timeout) {
  $scope.items = [1,2,3];
};
app.directive('focusMe', function($timeout) {
  return {
    scope: { trigger: '=focusMe' },
    link: function(scope, element) {
      scope.$watch('trigger', function(value) {
        if(value === true) { 
          //console.log('trigger',value);
          //$timeout(function() {
            element[0].focus();
            scope.trigger = false;
          //});
        }
      });
    }
  };
});

http://plnkr.co/edit/yZ21NYb5EkUTSAWOVjHZ?p =

预览

我不知道为什么,但不知何故使用scope: { trigger: '=focusMe' }做出了不同。有线索吗?

变化

app.directive('focusWhen', function($scope) {

app.directive('focusWhen', function() {