将文本区域重点放在ng-click上

时间:2014-03-11 05:30:23

标签: javascript html angularjs angularjs-ng-repeat

我想点击ng-repeat内的按钮,并关注循环中特定项textarea

HTML

<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. 点击后如何进行对焦?

  3. 感谢。

    更新1

    我使用下面的代码

    让这个工作

    HTML

    <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=preview

    我不确定为什么但是以某种方式使用scope: { trigger: '=focusMe' }做出了不同的看法。任何线索?

1 个答案:

答案 0 :(得分:0)

更改

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

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