Reputation: 424
I'm working with AngularJS 1.6 and a component based web application. I'm building a new component which contains a table and on selecting a row another stateless component is being displayed with detailed information about that rows' object (the row is passe down via '<'-binding). So far, it works. I'm using stateful and stateless components, and from Todd Motto I learned to use one way binding (also in preparation to migrate to Angular) and that to break JavaScripts' bind-by-reference I should use following event hook in the stateless component (the detail component in my specific case):
ctrl.$onChange = function(changes) {
if (changes.row) {
this.row = angular.copy(this.row);
}
};
It does work in the sense that changes in the child component do not change the object in the parent component anymore, cause the bind-by-reference is broken.
Problem is: If I select another row in the table, the changed object is NOT being passed down anymore, the stateless component does not "recognize" a changed object in the binding! If I ommit the above code it works, but will it still work when migrating to Angular? What should I do?
Upvotes: 0
Views: 228
Reputation: 48968
Copy the changes:
ctrl.$onChange = function(changes) {
if (changes.row) {
̶t̶h̶i̶s̶.̶r̶o̶w̶ ̶=̶ ̶a̶n̶g̶u̶l̶a̶r̶.̶c̶o̶p̶y̶(̶t̶h̶i̶s̶.̶r̶o̶w̶)̶;̶
this.row = angular.copy(changes.row.currentValue);
}
};
From the Docs:
Life-cycle hooks
Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the directive:
$onChanges(changesObj)
- Called whenever one-way (<
) or interpolation (@
) bindings are updated. ThechangesObj
is a hash whose keys are the names of the bound properties that have changed, and the values are an object of the form{ currentValue, previousValue, isFirstChange() }
. Use this hook to trigger updates within a component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will also be called when your bindings are initialized.
For more information, see
Upvotes: 1