I am encountering an issue while using multiple components on a composite page and trying to reference data from a common service. The main problem arises when I attempt to create the object in the service within the first component and then access it in the second component; if the second component is placed before the first one, the value object has not been instantiated yet causing the second component to fail to display anything.
Although I hoped that two-way data binding would resolve this issue, unfortunately, it did not.
Composite HTML
<second-component></second-component>
<first-component></first-component>
First Component
angular.
module('simple').
component('firstComponent', {
template: "<h3>Component 1</h3><ul ng-repeat='val in $ctrl.someVals'><li>{{val}}</li></ul>",
controller: function(factory) {
'use strict';
// Responsible for creating an object in the service
factory.changeData();
this.someVals = factory.vals;
}
});
Second Component
angular.
module('simple').
component('secondComponent', {
template: "<h3>Component 2</h3><ul ng-repeat='val in $ctrl.someVals'><li>{{val}}</li></ul>",
controller: function(factory) {
'use strict';
// As a sub-component, secondComponent depends on an object being present in the service. This
// will be created by firstComponent, which will reside on the same page.
this.someVals = factory.vals;
}
});
Factory Service
angular.
module('simple').
factory('factory', function() {
var data = {};
data.vals = {};
data.changeData = function() {
data.vals = {
"a": 11,
"b": 22,
"c": 33
};
};
return data;
});
I expect both component 2 and component 1 to reference the same data after it has been modified by component 1:
Component 2
- 11
- 22
- 33
Component 1
- 11
- 22
- 33
However, what actually happens is:
Component 2
Component 1
- 11
- 22
- 33
I am looking for a solution to instantiate objects in one component and share them with another component without worrying about their order on the page. In this scenario, timing plays a crucial role. Reversing the order of the components works fine, but visually I need my second component to come first. Instantiating the object in the service from the second component does not make sense as it should only rely on service state data without modifying it directly. Despite my initial belief, two-way data binding does not behave as expected when the first component alters the object in the service.
P.S. I am new to AngularJS. Any recommendations for reference materials or tutorials would be greatly appreciated!