2017-06-20 54 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

相关问题