在组件中如何调用作为绑定接收的控制器中的函数

In a component how to call a function in the controller that was received as a binding

我正在尝试创建一个组件,允许我对输入​​进行一些检查并延迟保存,以免对数据库造成太大压力。

这是我无法排序的部分的简化代码。 问题是 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>

这是我的 jsfiddle https://jsfiddle.net/fph33y20/

您必须使用 this 才能访问控制器内的绑定。默认情况下,可以在组件模板中使用 $ctrl 访问组件控制器的属性。回调也应该在父控制器中定义。

这是一个工作示例:

var app = angular.module('myApp', []);
app.controller('mainCtrl', ['$scope', '$window', function($scope, $window) {   
  this.alert = function(rate){ console.log(rate); }; 
  this.rateCol = {
   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>