簡體   English   中英

將文本區域放在ng-click上

[英]Focus textarea on ng-click

我想從ng-repeat單擊一個按鈕,然后將重點放在循環中該特定項目的 textarea

的HTML

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

Java腳本

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

我使用下面的代碼來工作

的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>

Java腳本

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' }有所不同。 有什么線索嗎?

更改

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM