As a newcomer to Angular, I am facing challenges in understanding how to utilize a Service to transfer data from one controller to another.
My experience with Angular so far has involved successfully calling controllers and passing data to them from within HTML. This has been particularly useful in setting up a Map Controller, where I extract results from PHP and send the data to my controller to create map markers.
However, I am struggling with passing data from one controller that generates a nested object through an ElasticSearch call to my Map Controller.
Initially, I attempted to loop through the results using ng-repeat. While I could display the results, my MapController couldn't access them in the HTML, I suspected this was due to the constraints of my IndexController.
Although I managed to output the data, I couldn't 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>
After researching, I found that the recommended way to pass data between controllers is through a service. However, despite following documentation, I seem to be missing something as it is not functioning as intended.
This is what I have implemented so 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 (currently just attempting to display the object)
App.controller('MapController', function($scope, resultsService) {
$scope.locations = resultsService.getLocations();
alert($scope.locations);
This is a snippet of the object 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"}
]};