2016-03-17 80 views
5

我是angularjs的新手。我正在嘗試角1.5嵌套組件。我可以在子組件中綁定父組件屬性嗎?Angular 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使用組件,您可以通過require讓你的父母組成的持有這將提供父母的屬性後$onInitComponents Documentation爲:

注意, 過程中所需的控制器將不可用控制器的實例化,但它們保證在執行$ 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工作...所以這裏的代碼......從我的index.html文件 提取

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

的js文件

(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所示。

基本上,您可以定義子組件定義綁定功能,像這樣,

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

然後,在你提供一個函數調用父類的標記,

父HTML

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

最後,在父控制器中,提供selectUser函數的實現。

這裏有一個工作Plunk