Reputation: 1500
My app consists of several controllers. Each of them gathers different data into its scope
object. Now I'm changing the way of dealing with the data so having the data separated is no longer an option (the goal is to have the data sent to a PHP script for PDF conversion).
That being said, I need a way to either have them sent via POST altogether or to have them first combined into a single object and then sent.
I've just found out about angular.extend but I'm unsure if this supports combining objects coming from different controllers and if it does - how and where is it accomplished?
Should it be a new controller, a service or something else?
Upvotes: 0
Views: 926
Reputation: 37701
No need to complicate things, this is the perfect use for a service (or a factory). Services are singletons, so you won't have to worry about instantiating the same one from each controller - just make a function that will group and gather the data from all the controllers and you're good to go.
Every controller will also have access to this data, so sending it to PHP won't be an issue as well.
Simple example:
angular.module('app', [])
.controller('CtrlOne', function(myService) {
myService.sendData('some data');
})
.controller('CtrlTwo', function(myService) {
myService.sendData('even more data');
})
.service('myService', function() {
var gatheredData = [];
return {
sendData: function(data) {
gatheredData.push(data);
alert('Current data: ' + gatheredData.join(', '));
},
getData: function() {
return gatheredData;
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="CtrlOne"></div>
<div ng-controller="CtrlTwo"></div>
</div>
Upvotes: 2