I'm trying to component-ise my codebase and have come up stuck on this problem.
When using $scopes and Controllers I would pass a server token to my rest call method with ng-init. Trying to do the same with a Component is not working.
javascript
angular
.module('myApp', [])
.controller('mainCtrl', function() {
var self = this;
self.options = function() {
var o = {}
o.token = self.serverToken
return o;
}
self.restData = {
url: 'http://rest.url',
options: self.options()
}
})
.component('myComponent', {
bindings: {
restData: '<'
},
template: '<p>template, calls child components</p>',
controller: function(restService) {
this.callRestService = function() {
restService.get(this.restData.url, this.restData.options)
}
console.log(this.restData.url) // http://rest.url
console.log(this.restData.options) // {token: undefined}
}
})
html
<html ng-app="myApp">
<!-- head -->
<body ng-controller="mainCtrl as m" ng-init="m.serverToken='12345'">
<my-component rest-data="m.restData"></my-component>
</body>
</html>
How do I pass the value to the component?
The issue is that the ng-init is executed after the controller is instantiated. However you are creating your restData object during the construction of your controller at which time the serverToken is undefined.
You could build your restData object after ng-init is called with something like this:
Your component can then do something when that restData changes. For example:
The HTML would change to call your init method: