2016-09-27 16 views
0

親コントローラのコンテキストでgetDataInParentが呼び出される必要があります。親のコンテキストで親コントローラの関数を呼び出す

サンプル:

子ディレクティブが正しく親ディレクティブのテンプレートの中から、このような設定である:

<child get-data="parentCtrl.getDataInParent"></child> 

そして、ここでは私のコントローラの実装の簡単なモックアップ(getDataInParentのコメントを参照してください)

// *** parent controller 
controller('parentController', [...., function(){ 

var that = this; 
that.someData = ...; 

that.getDataInParent = function(someArgs){ 
    // Here I need to access "that.someData" and other 
    // properties/methods of this parent controller. But I can't! 
    // Because this method doesn't seemed to be called in the context of this controller. 
}; 
};] 

// *** child controller 
controller('childController', [...., function(){ 

var that = this; 

// Hooked up correctly and am able to call the parent's function like this: 
var dataFromParent = $scope.getData().(someArgs); 
};] 

これは非常に一般的なシナリオのように多くの人が遭遇したと思われるので、私はまっすぐ進むべきであると期待しています。これのためのlutionは角度で。

+0

私たちのディレクティブの宣言を表示します。一般的なアプローチは、関数を独立したスコープに渡すことです。新しいバージョンのangleでも 'bindToController'を使うことができます。問題を再現するデモを作成します。いつでも[mcve] – charlietfl

+0

チャーリーを提供する必要があります、私はオンラインサンプルを作成しようとします。何が最高の場所でしょうか?プランカ? –

+0

Plunker is very easyはい – charlietfl

答えて

1

は、あなたは、常にこの「&」を使用してローカルスコープの親関数をバインド&ディレクティブのローカルスコープを作成することができます。これが自分のHTMLだとします。

<child get-data="parentCtrl.getDataInParent(params)"></child> 

これはあなたの指示コードです。

angular 
    .module('SampleApp') 
    .directive('child', child); 

/* @ngInject */ 
function child() { 
    var directive = { 
     restrict: 'E', 
     templateUrl: 'templateUrl', 
     scope: { 
      getData : '&' 
     }, 
     link: linkFunc, 
     controller: 'Controller', 
     controllerAs: 'vm' 
    }; 

    return directive; 

    function linkFunc(scope, el, attr, ctrl) { 
     // Calling parent method here 
     var dataFromParent = $scope.getData({params: "SomeParams"}); 
    } 
} 

ワーキングPlunker:https://plnkr.co/edit/4n61WF4JN3eT2QcdnnTw?p=preview

+0

ササンクこれは私がすでにセットアップしている方法です。そして、私が元の郵便で言及している問題はそのままです。あなたのプロジェクトのいずれかにこのようなことがある場合は、同じ問題をそこに見るのはとても簡単でしょう。 –

+0

こちらが実行されています。https://plnkr.co/edit/4n61WF4JN3eT2QcdnnTw?p=preview –

+0

はい、うまくいくようです。ありがとう。私のコードについて何が違うのか調べてみましょう。 –

関連する問題