2017-06-20 75 views
0

我想通過我的組件傳遞一個值到我的控制器,但我仍然得到這個未定義的消息。我錯過了什麼嗎?如何將值傳遞給使用組件的控制器?

myhtml.html

<my-component item="value1"></my-component> 
<my-component item="value2"></my-component> 
<my-component item="value3"></my-component> 

mycomponent.js

angular 
    .module('mycomponent.component', [ 
     'mycomponent.controller' 
    ]) 
    .component('myComponent', { 
     templateUrl: 'components/mycomp/mycomp.component.html', 
     controller: 'ComponentController', 
     controllerAs: 'componentVM', 
     replace: true, 
     bindings: { 
      item: '=' 
     } 
    }); 

mycontroller.js

angular 
    .module('mycomponent.controller', []) 
    .controller('ComponentController', ComponentController); 

    ComponentController.$inject = []; 

    function ComponentController() { 
     var vm = this; 
     console.log('item value> ' + vm.item); // This is got undefined :(
    } 
+0

您需要在'this。$ onInit = function(){/ * bound properties available here * /}內放置'console.log()'(或者任何使用vm.item的東西)' – mhodges

回答

1

至於建議在@mhodges的評論中將您所有的邏輯 放在$onInit掛鉤中。 $onInit作爲組件生命週期的一部分在所有綁定初始化時觸發。

var self = this; 
self.$onInit = function(){ 
    console.log('item value> ' + self.item); 
} 

回到你的代碼,如果value1是你應該使用一個單一的方式結合@(原始類型不能使用雙向綁定,因爲它們不是引用)

bindings: { 
    item: '@' 
} 

<my-component item="value1"></my-component> 

基本類型在場景中item是一個對象,要將組件與外部環境分離,最好使用單向綁定。<,

bindings: { 
    item: '<' 
} 

這甚至會遵循Angular> 1.5的指導原則,以構建基於組件的架構。

從角1.5 DOC:

輸入應該使用<和@綁定。 <符號表示從1.5開始可用的單向 綁定。到=所不同的是 在組件範圍結合的性質不觀看,如果分配一個新的值對組成 範圍的屬性,該屬性 裝置,也不會更新父範圍

https://docs.angularjs.org/guide/component

+0

同樣重要的是,引用綁定值的任何內容都在'this。$ onInit()'函數內部。在組件被初始化並且$ onInit被觸發之前,綁定值將是未定義的。這實際上是OP爲什麼會遇到未定義問題的答案。這不是因爲他們如何使用「綁定」,儘管你的建議很好。 – mhodges

+1

你是對的,我已經解決了我的答案;) – Karim

相關問題