I\'m writing an Angular 1.5 directive and I\'m running into an obnoxious issue with trying to manipulate bound data before it exists.
Here\'s my code:
ap
The original poster said :
the promise is being fulfilled even before the binding is populated... sot hat by the time I run the loop, ctrl.forms is still undefined
Ever since AngularJS 1.5.3, we have lifecycle hooks and to satisfy the OP's question, you just need to move the code that is depending on the bindings being satisfied inside $onInit()
:
$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.
So in the example:
app.component('formSelector', {
bindings: {
forms: '='
},
controller: function(FormSvc) {
var ctrl = this;
this.favorites = [];
this.$onInit = function() {
// At this point, bindings have been resolved.
FormSvc
.GetFavorites()
.then(function(results) {
ctrl.favorites = results;
for (var i = 0; i < ctrl.favorites.length; i++) {
for (var j = 0; j < ctrl.forms.length; j++) {
if (ctrl.favorites[i].id == ctrl.newForms[j].id) {
ctrl.forms[j].favorite = true;
}
}
}
});
}
}
So yes there is a $onChanges(changesObj)
, but $onInit()
specifically addresses the original question of when can we get a guarantee that bindings have been resolved.