I have a situation where I am using a factory to make a call in two controllers on the same page. However, I want to avoid making an AJAX call twice. I tried using $q.defer(), but it doesn't seem to be working!
Here is the code snippet:
(function () {
'use strict';
var app = angular.module('globalApp', []).config([
'$interpolateProvider', '$httpProvider',
function ($interpolateProvider, $httpProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
}
]);
// Index Store List
app.controller('IndexController', ['$scope', '$storeList',
function ($scope, $storeList) {
$scope.stores = [];
$storeList.getStoreList().then(function (stores) {
$scope.stores = stores;
});
}]);
// Footer Store List
app.controller('StoreListController', [
'$scope', '$storeList',
function ($scope, $storeList) {
$scope.stores = [];
$storeList.getStoreList().then(function (stores) {
$scope.stores = stores;
});
}
]);
// Factory call list of stores
app.factory('$storeList', function ($http, $q) {
var stores = [];
return {
getStoreList: function () {
if (stores.length > 0) {
var deferred = $q.defer();
deferred.resolve(stores);
return deferred.promise;
}
var uri = rootUrl + 'getStoreList';
var responsePromise = $http.get(uri);
return responsePromise.then(function (result) {
var data = result.data;
if (data.status) {
var stores = data.stores;
return stores;
}
});
}
};
});
}());
<body ng-app="globalApp">
<section>
<div ng-controller="IndexController">
<nav>
<a ng-repeat="store in stores" href="<%store.link%>"><%store.name%></a>
</nav>
</div>
</section>
<footer>
<div>
<ul ng-controller="StoreListController">
<li ng-repeat="store in stores">
<h3><a href="<%store.link%>"><%store.name%></a></h3>
<p>
<%store.street%>, <%store.number%>
<%store.neighborhood%>, <%store.cityName%>
<a><%store.phone%></a>
<a><%store.email%></a>
</p>
</li>
</ul>
</div>
</footer>
</body>