I'm working on sharing objects between controllers in AngularJS and while I've come up with a solution that works, it doesn't feel very elegant to me. I'm curious if there is a better way to accomplish this task rather than the one I have implemented.
Specifically, in componentA, I have an object that needs to be accessed from componentB.
app.component("componentA", {
controller: function ($scope, $rootScope, $compile) {
//the object that needs to be shared
$scope.objectToAccess = {name: 'object', value: 3};
//listens for broadcast from componentB and passes the object
$rootScope.$on("getObject", function () {
$rootScope.$broadcast('receiveObject', $scope.objectToAccess);
});
}
}
app.component("componentB", {
controller: function ($scope, $rootScope, $compile) {
$scope.object = {name : null, value: null};
//receives the broadcasted object and assigns its value
$rootScope.$on("receiveObject", function (event,object) {
console.log(object);
$scope.object = object;
});
//broadcasts to request the object's contents
$rootScope.$broadcast('getObject');
}
}
The current setup works, but I find it too complex with all the back and forth communication. Are there any Angular features specifically designed for handling such scenarios, or is my approach justified?