Reputation: 1877
I'm trying to pass a value to my controller trough my component but im still getting this undefined message. Am I missing something?
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 :(
}
Upvotes: 0
Views: 41
Reputation: 8632
As suggested in the comments by @mhodges put all your logic
inside the $onInit
hook.
$onInit
is triggered as part of the component life cycle when all your bindings are initialized.
var self = this;
self.$onInit = function(){
console.log('item value> ' + self.item);
}
Back to your code, if value1
is a primitive type you should be using a single way binding @
(primitive type cannot use a two way binding as they aren't references)
bindings: {
item: '@'
}
<my-component item="value1"></my-component>
In a scenario where item
is an object, to decouple the component from the outer environment it would be better to use a one way binding <
,
bindings: {
item: '<'
}
this would even follow the guidelines of Angular > 1.5 that aim to a component based architecture.
From Angular 1.5 doc:
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
https://docs.angularjs.org/guide/component
Upvotes: 1