【问题标题】:Calling Parent Controller From Angular Directive从 Angular 指令调用父控制器
【发布时间】:2014-09-25 22:47:32
【问题描述】:

简而言之,我试图将指令中的数据集传递回其父控制器。我已经看到了这方面的几个细微差别,但是在某个地方我遗漏了一些东西,而且我正在做的事情并不完全奏效。我有一个从父级接收回调定义的指令,如下所示:

<my-directive my-list="myData" update-parent="parentCallback(newData)">

父控制器的回调很简单,但是传入的数据是空的:

$scope.parentCallback = function(newData) { /* when it gets here its null */ };

指令的定义是这样的:

myModule.directive('myDirective', function() {
return {
    restrict: 'E',
    templateUrl: 'Template.html',
    replace: true,
    scope: { myData: '=', updateParent: '&' },
    controller: function($scope, $element, $attrs) {...}

指令控制器中的选择事件尝试通过回调将数据推回,如下所示:

$scope.updateSelection = function() {
    /* here the data is good */
    $scope.updateParent($scope.currentSelection);
};

当前选择变量在指令范围内定义,并通过下拉列表框上的选择进行设置。发生的情况是,在上面的函数中,它调用了父回调,发现它没问题,传递了好的数据,但是当它到达父端时,参数为空。我对此并不陌生,但我认为“&”可以让我将数据传递回父级。任何帮助将不胜感激!

【问题讨论】:

  • 能否让我知道我的回答是否解决了您的问题,如果可以,请您接受答案吗?谢谢!

标签: angularjs angularjs-directive


【解决方案1】:

为了将参数传递给绑定的function,参数必须作为对象传递,对象的键是否是绑定函数的参数名称,如下所示:

$scope.updateSelection = function() {
    $scope.updateParent({newData:$scope.currentSelection});
};

【讨论】:

  • 这完全有道理。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-03
  • 2013-03-15
相关资源
最近更新 更多