Angular: Empty Fiddle
http://angularjs.org/
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<button ng-click="getcity('ABCDE')">
GET CITY 1!!
</button>
<button ng-click="getcity('DEFG')">
GET CITY 2!!
</button>
<pre>{{cities | json}}</pre>
</body>
JavaScript
console.clear()
var myApp = angular.module("myApp", []);
// add a controller
myApp.controller("myCtrl", function($scope, cityService) {
$scope.cities = {};
var pending = {};
$scope.getcity = function(code){
if(!pending[code]){
pending[code] = true
cityService.getCities(code).then(function(risp){
console.log("ctrllog",risp)
$scope.cities[risp.name] = risp;
pending[code] = false;
})
}
}
})
.service("cityService", function($http, $q, $httpParamSerializerJQLike){
//var callCache = {};
var cityCache = {};
return {
getCities: function(countryCode){
//if(callCache[countryCode] === undefined){
var promise = $q.defer();
// callCache[countryCode] = promise;
//}else{
// console.log("return cached promise!!", callCache[countryCode]);
// return callCache[countryCode].promise;
//}
if (countryCode!=undefined && !cityCache[countryCode]) {
console.log("new city");
var data = $httpParamSerializerJQLike({
json: JSON.stringify({
name: countryCode+Math.random().toString(36).substring(7)
})
});
$http({
method: 'POST',
url:"/echo/json/",
data: data
}).then(function(risp) {
console.log("servicelog",risp.data);
cityCache[countryCode] = risp.data;
var obj = angular.extend({cache: false}, risp.data);
promise.resolve(obj);
//callCache[countryCode].resolve(obj);
//delete callCache[countryCode];
});
}else{
setTimeout(function(){
var obj = angular.extend({cache: true}, cityCache[countryCode]);
...