我正在尝试通过我的组件将值传递给我的 Controller ,但我仍然收到此未定义的消息。我错过了什么吗?
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 :(
}
最佳答案
正如 @mhodges 的评论中所建议的,把你所有的逻辑
里面$onInit
钩。
$onInit
当所有绑定(bind)都初始化时,作为组件生命周期的一部分触发。
var self = this;
self.$onInit = function(){
console.log('item value> ' + self.item);
}
回到你的代码,如果 value1
是一个原始类型,您应该使用单一方式绑定(bind) @
(原始类型不能使用双向绑定(bind),因为它们不是引用)
bindings: {
item: '@'
}
<my-component item="value1"></my-component>
在 item
的场景中是一个对象,要将组件与外部环境解耦,最好使用单向绑定(bind) <
,
bindings: {
item: '<'
}
这甚至会遵循 Angular > 1.5 的准则,旨在基于组件的架构。
来自 Angular 1.5 文档:
Inputs should be using < and @ bindings. The < symbol denotes one-way bindings which are available since 1.5. The difference to = is that the bound properties in the component scope are not watched, which means if you assign a new value to the property in the component scope, it will not update the parent scope
关于javascript - 如何使用组件将值传递给 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44641688/