JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-mocks.js"></script>
<div ng-app="app">
<div ng-controller="myCtrl">
<h1>
{{ user_curr.code }}
<select ng-options="currency as currency.name for currency in currencies" ng-model="user_curr">
</select>
</h1>
</div>
<div ng-controller="myCtrl">
<h1>
{{ user_curr.code }}
</h1>
</div>
<div ng-controller="myCtrl">
<h1>
{{ user_curr.code }}
</h1>
</div>
<div ng-controller="myCtrl">
<h1>
{{ user_curr.code }}
</h1>
</div>
</div>
JavaScript
var app = angular.module("app", ["ngMockE2E"]);
app.run(function($httpBackend) {
$httpBackend.whenGET("/currencies")
.respond(function(method, url, params) {
var currencies = [{
id: 1,
name: "EUR",
code: "EUR"
}, {
id: 2,
name: "Dollar",
code: "$"
}, {
id: 3,
name: "Roebel",
code: "&@"
}];
console.log("Calling currency api..");
return [200, currencies];
});
});
app.controller("myCtrl", ["$scope", "currencyService", function($scope, currencyService) {
currencyService.getCurrencies().then(function(currencies) {
$scope.user_curr = currencies[0];
$scope.currencies = currencies;
});
}]);
app.service("currencyService", function($q, $http) {
var _currencyPromise = null,
_currencies = null;
this.getCurrencies = function() {
var deferred = $q.defer();
// Check if the currencies are resolved before
// If so, immediately return these
if (_currencies) {
deferred.resolve(_currencies);
}
// Else check if the promise is already running
// If so, use that promise
else if (_currencyPromise) {
_currencyPromise.then(function(response) {
deferred.resolve(response.data);
});
}
// Else make the http call and assign to the promise
// So that the promise can be used instead of a new http call
else {
_currencyPromise = $http.get("/currencies");
_currencyPromise.then(function(response) {
// Assign data to the currencies, so that it can be used
// by next calls immediately
_currencies = response.data;
deferred.resolve(_currencies);
}, function(error) {
// something went wrong
_currencyPromise = null;
deferred.reject();
});
}
return deferred.promise;
}
});