I recently updated my app from angularjs 1.5.9 to angularjs 1.7.9. In one of my controllers I had the following code:
angular.module( 'myModule' )
.component( 'dynamicContent', {
bindings: {
pageTitle: '<',
content: '<',
type: '<',
width: '<'
},
templateUrl: 'path/to/html/file',
controllerAs: 'dynamic',
controller: function( $state, $window, Contentful ) {
var vm = this;
vm.$onInit = _init();
function _init() {
vm.items = _.map( vm.content, mapContent );
}
After updating to 1.7.9 the vm.items variable was never getting defined because the vm.content was undefined in the _init function. However, after changing the code to...
angular.module( 'myModule' )
.component( 'dynamicContent', {
bindings: {
pageTitle: '<',
content: '<',
type: '<',
width: '<'
},
templateUrl: 'path/to/html/file',
controllerAs: 'dynamic',
controller: function( $state, $window, Contentful ) {
var vm = this;
vm.$onInit = function _init() {
vm.items = _.map( vm.content, mapContent );
}
This now works. Can anyone explain why defining the function where I set it to $onInit makes this work? Thanks!
vm.$onInit = _init();
This is equal to simple _init();
, you probably meant vm.$onInit = _init
.
In 1.5 you can run init yourself and there was no real difference, but in latest Angularjs bindings are set after your controller main function, but before on init, e.g.:
bindings: { test: '<'}
controller: () => {
var vm = this;
console.log(vm.test); // undefined
vm.$onInit = () => {
console.log(vm.test); // has value
}
}