I'm new to angular and am struggling to get to understand how to use a Service to pass data from one controller to another.
So far with with Angular, I have been able to understand how to call controllers and pass data to them from within HTML. That's been especially fine in order to set up a Map Controller, whereby I look through a list of results that comes from PHP, and send data from those results into my controller, to create markers on a map.
What has me completely stumped, is having one controller that generates a nested object via a ElasticSearch call and then passing that data to my Map Controller.
Initially I tried looping through the results via ng-repeat, and while I was able to output the results, my MapController wasn't able to read those results in the HTML as they were within the confines of my IndexController (which was outputting the data). Well I assume that was the case.
This is what I tried, and while it outputted the data, I could never read it in MapController.
<div ng-controller="IndexController">
<div ng-repeat="r in listingsArea.results">
<div class="component home-listings"
data-id="{{r.id}}"
data-url="{{r.url}}"
data-lat="{{r.lat}}"
data-lng="{{r.lon}}"
data-address="{{r.address}}"
data-price="{{r.price}}"
></div>
</div>
</div>
I've read that the best way to pass data from one controller to another is via a service. I've followed a lot of documentation here, but despite this I am obviously missing something as it is not working.
This is what I have thus far:
ResultsService.js
App.factory("resultsService", function() {
var loadListingsArea = {};
return {
getLocations: function() {
return loadListingsArea
},
setLocations: function(loc) {
loadListingsArea = loc;
IndexController.js
App.controller('IndexController', function($scope, resultsService) {
$scope.listingsArea = [];
$scope.loadListingsArea = function() {
$http.get($window.location + '/listingsarea')
.success(function(data) {
$scope.listingsArea = data;
}
);
}
$scope.$watch(function() {
return $scope.loadListingsArea;
}, function() {
resultsService.setLocations($scope.loadListingsArea);
});
});
MapController.js (just trying to dump the object at this stage, not including my very long code base for the google map)
App.controller('MapController', function($scope, resultsService) {
$scope.locations = resultsService.getLocations();
alert($scope.locations);
This is a sample of what my object looks like when dumped from indexcontroller.js
{"count":4,
"results":[
{"id":"1153292",
"url":"/this-is-my-slug/1153292",
"lat":"-37.822034",
"lon":"144.969553",
"address":"1302/430 Place Road",
"price":"$2,350,000",
"hero":"some-image-here.jpg"}
]};