2016-03-17 19 views
5

私はangularjsを初めて使用しています。私は角度1.5のネストされたコンポーネントを試しています。子コンポーネントの親コンポーネントプロパティをバインドできますか?角度1.5ネストされたコンポーネントバインド親値

例:

<div ng-app='cbsApp' ng-controller='cbsCnt as ct'> 
    <cbs-cus-comp com-bind='ct.name'> 
     <child child-com-bind='cbsCusCompCntAs.name'></child> 
    </cbs-cus-comp> 
</div> 

私は、COM-バインドでct.name値を得ることができます。しかし、child-com-bindではcbsCusCompCntAs.nameを取得できません。 (cbsCusCompCntAsはCBS-CUS-COMPコントローラ)

ワーキングPlunker:予めhttps://plnkr.co/edit/axQwTn?p=preview

おかげ。

答えて

6

最初のケースでは、controllerAs経由でコントローラのスコープを直接参照しています。角度1.5のコンポーネントを使用する場合は、あなたがComponents Documentationごとに$onInit後に親の性質を利用可能になるrequireを経由して、あなたの親コンポーネントを手に入れることができます

:必要なコントローラが 中に使用できないこと

注意コントローラのインスタンス化が行われますが、$ onInitメソッドが実行される直前には が使用できることが保証されています。あなたが親を必要とするコンポーネント更新することができ、あなたの特定のケースで

:必要なデータを取得するのに

var child = { 
    require  : {parentComp:'^cbsCusComp'}, 
    template : 'Child : <b{{cbsCusChildCompCntAs.childComBind}}</b>', 
    controller : cbsCusChildCompCnt, 
    controllerAs: 'cbsCusChildCompCntAs' 
    }; 

とそのコントローラを(私はちょうどにあなたと同じ名前を使用それは)働く参照:

function cbsCusChildCompCnt(){ 
    this.$onInit = function() { 
    this.childComBind = this.parentComp.name; 
    }; 
} 

更新plunkerがhereです。

4

うわー...なんとすばらしい例... 私はそれを分析するためにしばらく時間をかけました...だから、私は自分の(私は少し読みやすいと思う)バージョンを書いた。 私は本当にPlunkerで動作する方法がわからない...ので、ここでのコード...

<div ng-controller='appCtrl as ctrl'> 
    <parent bind-id='ctrl.name'> 
     <child bind-toid='parentCtrlAs.name'></child> 
    </parent> 
</div> 

の.jsファイルは私のindex.htmlファイルから extractの

(function() { 
'use strict'; 

var 
    parentComponent = 
    { 
     bindings : 
     { 
      bindId:'=' 
     }, 
     controller : parentCtrl, 
     controllerAs: 'parentCtrlAs', 
     restrict : 'A', 
     transclude : true, 
     templateUrl : 'parent.html', 
    }; 

var 
    childComponent =  
    { 
     controller : childCtrl, 
     controllerAs: 'childCtrlAs', 
     restrict : 'A', 
     require  : 
     { 
      myParent :'^parent' 
     }, 
     templateUrl : 'child.html', 
}; 


angular 
    .module('app', []) 
    .controller('appCtrl' , appCtrl) 
    .component('parent'  , parentComponent) 
    .component('child'  , childComponent); 


function appCtrl(){ 
    this.name = 'Main..'; 
} 

function childCtrl(){ 
    this.$onInit = function() { 
     this.bindToid = this.myParent.name; 
    }; 
} 

function parentCtrl(){ 
    this.name = 'Parent Component'; 
} 

})();パラメータ作品を「必要」を使用して、それが「必要」パラメータ、および使用する、子として動作するコンポーネント間の強固に結合関係が作成されますが、

3

それが役に立てば幸い、 よろしく、 ジョニー親として機能するコンポーネントであり、子機能を消費する。

もっと良い解決策は、hereのようにコンポーネント通信を使用することです。

基本的に、あなたが親HTML

、親マークアップであなたが呼び出すための機能を提供し、そして、そのような、

angular.module('app').component('componentName', { 
templateUrl: 'my-template.html', 
bindings: { 
     myFunction: '&' 
}, 
controller: function() { // Do something here} 
}); 

、子コンポーネント定義で結合機能を定義します

<user-list select-user="$ctrl.selectUser(user)"> 
 
</user-list>

最後に、親コントローラで、selectUser関数の実装を提供します。

ここには、作業中のPlunkがあります。

関連する問題