JSFiddle - React, Tailwind, and code Playground
by PeterShafer
HTML
<div ng-app="angularApp" ng-controller="demo as demo">
<h1>{{ data.title || 'title unavailable' }}</h1>
<p>{{ data.body || 'body unavailable' }}</p>
<h2>The myResource service has...</h2>
<ul>
<li>...made HTTP calls <em>{{ timesRequested || 0 }}</em> times.</li>
<li>...been called <em>{{ timesCalled || 0 }}</em> times.</li>
</ul>
<h2>Call the service again...</h2>
<p>
<button ng-click="demo.clear()">Clear Data</button>
<button ng-click="demo.call()">myResource.get()</button>
</p>
</div>
JavaScript
angular.module('angularApp', [])
.service('myResource', function myResource($http, $rootScope) {
var promise;
var timesRequested = 0;
var timesCalled = 0;
return {
get: function(){
timesCalled++;
if (!promise) {
timesRequested++;
var url = 'http://jsonplaceholder.typicode.com/posts/1';
promise = $http.get(url);
}
$rootScope.timesRequested = timesRequested;
$rootScope.timesCalled = timesCalled;
return promise;
}
};
})
.controller('demo', function demo($rootScope, myResource) {
this.call = function(){
myResource.get().success(function(data){
$rootScope.data = data;
});
};
this.clear = function(){
$rootScope.data = {};
};
})