Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.5 component onChanges is not working

Tags:

Since we have pretty big Angular 1.x application, we can't upgrade it fully to Angular 2 but I love the new architecture. Version 1.5 brings amazing components to the old same app. As all cool stuff, it lacks documentation ;-)

So, here is a question. I have those two lines in the controller's definition:

this.$onInit = setType; this.$onChanges = setType; 

the first is working, whilst the second isn't. I am using '<' binding. So on the first load, the component's state is set according to passed values, whilst the changes are not being reflected. I got the hope that it should work from [1] and [2].

[1] https://docs.angularjs.org/guide/component

[2] https://angular.io/docs/js/latest/api/core/OnChanges-interface.html

UPD Ok, I have learnt that it is not supposed to work: https://github.com/angular/angular.js/issues/14030

Does anybody know good workarounds?

UPD2 It works as of 1.5.3

like image 842
leitasat Avatar asked Feb 24 '16 14:02

leitasat


1 Answers

As of AngularJs 1.5.3, supposing ctrl.someModel is bound one-way in a child component, the following won't trigger $onChanges.

function get() {    api.getData().then( (data) => {     ctrl.someModel.data = data   } } 

It seems like updating properties of an object won't be recognized as an update.

This is how I currently get around it. I don't believe it to be the best solution, but it triggers $onChanges. I create a deep copy of my initial model, add the data as one of it's properties, and then set my initial model to the value of the new object. Essentially, I update the whole object, which is picked up by the lifecycle hook:

function get() {    api.getData().then( (data='42') => {     const updatedModel = angular.copy(ctrl.someModel)     updatedModel.data = data     ctrl.someModel = updatedModel   } } 

And in the child component (assuming the model as been binded as 'data'):

this.$onInit = function(bindings) {   if (bindings.data && bindings.data.currentValue) {     console.log(bindings.data.currentValue) // '42'    } } 
like image 95
Jonathan Dupré Avatar answered Nov 18 '22 17:11

Jonathan Dupré