When it comes to having a shared object across a component hierarchy, using services as singletons is not the way to go. Instead, you can utilize requires to access an instance of a parent component and have the shared object linked to that component's controller.
angular.module('app', []).component('parentComponent', {
template: 'Parent<br><ng-transclude></ng-transclude>',
transclude: true,
controller: function() {
this.sharedData = {
rnd: Math.random() * 10
};
}
}).component('childComponent', {
template: 'child {{ $ctrl.parentCtrl.sharedData.rnd }}',
require: {
parentCtrl: '^parentComponent'
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app">
<parent-component>
1. <child-component></child-component><br>
2. <child-component></child-component><br>
</parent-component><br>
<parent-component>
3. <child-component></child-component><br>
4. <child-component></child-component><br>
</parent-component>
</div>
By observing how the children components extract the same instance within a component while obtaining another instance within another component, we can see the flexibility in managing shared objects efficiently.