2017-11-01 11 views
0

私は入力に対して何らかのチェックを行い、何らかの遅延を伴って保存してストレスを与えないようにするコンポーネントを作成しようとしていますあまりにも多くのデータベース。バインディングとして受け取ったコントローラ内の関数を呼び出す方法

これは私がソートできない部分の簡略化されたコードです。 問題は、updateFunctionが未定義であることです。どうすればアクセスできますか?

var app = angular.module('myApp', []); 
    app.controller('mainCtrl', function($scope) { 
    $scope.value = 2; 
}); 


app.component('saveDelay', { 
    restrict: 'E', 
    template: '<input type="text" ng-model="inputValue" />', 
    bindings: { 
    inputValue: '=', 
    updateFunction: '&' 
    }, 
    controller: function($scope) { 

    var saveTimer; 

    $scope.$watch('inputValue', 
     function(newValue, oldValue) { 

     if (newValue === oldValue) 
      return; 

     clearTimeout(saveTimer); 
     saveTimer = setTimeout(updateFunction, 1000); 
     } 
    ); 
    } 
}); 

HTML:

<div ng-app="myApp" ng-controller="mainCtrl"> 
    <save-delay input-value="value" update-function="Alert(value)" /> 
</div> 

ここでは、それはあなたのコントローラのプロパティではありませんので、あなたのコードupdateFunctionで私のjsfiddle https://jsfiddle.net/fph33y20/

答えて

2

をあなたは、コントローラ内のバインディングにアクセスするためにthisを使用する必要があります。デフォルトでは、コンポーネントコントローラのプロパティは、コンポーネントのテンプレート内に$ctrlでアクセスできます。コールバックは、親コントローラでも定義する必要があります。ここで

は実施例である:

var app = angular.module('myApp', []); 
 
app.controller('mainCtrl', ['$scope', '$window', function($scope, $window) { 
 
    this.alert = function(rate){ console.log(rate); }; 
 
    this.rateCol = { 
 
    \t rate: 10 
 
    }; 
 
}]); 
 

 

 
app.component('saveDelay', { 
 
    restrict: 'E', 
 
    template: '<input type="text" ng-model="$ctrl.inputValue" />', 
 
    bindings: { 
 
    inputValue: '=', 
 
    updateFunction: '&' 
 
    }, 
 
    controller: function($scope) { 
 
    var ctrl = this; 
 

 
    var saveTimer; 
 

 
    $scope.$watch(function(){ return ctrl.inputValue; }, 
 
     function(newValue, oldValue) { 
 

 
     if (newValue === oldValue) 
 
      return; 
 

 
     clearTimeout(saveTimer); 
 
     saveTimer = setTimeout(function(){ ctrl.updateFunction({rate: newValue}); }, 1000); 
 
     } 
 
    ); 
 
    } 
 
});
<div ng-app="myApp" ng-controller="mainCtrl as mc"> 
 
    <save-delay input-value="mc.rateCol.rate" update-function="mc.alert(rate)" /> 
 
</div> 
 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

0

は未定義です。好きなように使用するには、キーワードbindToControllerを使用できます。あなたのコントローラのthis.updateFunctionは、あなたの指令のパラメータin passの値で埋められます。これはあなたのコードになって変更すると:

app.component('saveDelay', { 
     restrict: 'E', 
     template: '<input type="text" ng-model="inputValue" />', 
     bindings: { 
     inputValue: '=', 
     updateFunction: '&' 
     }, 
    bindToController: true, 
     controller: function($scope) { 
     var vm = this; 
     var saveTimer; 

     $scope.$watch('inputValue', 
      function(newValue, oldValue) { 

      if (newValue === oldValue) 
       return; 

      clearTimeout(saveTimer); 
      saveTimer = setTimeout(this.updateFunction, 1000); 
      } 
     ); 
     } 
関連する問題