Lazy load factory singleton
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
<div ng-controller="mainCtrl">
<ul>
<li ng-repeat="thing in data">
{{thing.value}} - <button ng-click="clickMe(thing)">Click me</button>
</li>
</ul>
</div>
JavaScript
/* myApp module */
var myApp = angular.module('myApp', [])
myApp.controller('mainCtrl', function ($scope, serviceWithLongCall) {
$scope.data = [
{value: 69}, {value: 70}, {value: 71}, {value: 72}
];
$scope.clickMe = function (variable) {
serviceWithLongCall.call().then(function (data) {
variable.value = data;
});
}
});
myApp.factory('serviceWithLongCall', function ($q, $timeout) {
var data = {}
var hasStarted = false;
var deferred = $q.defer();
return {
call: call
};
function call() {
if (!hasStarted) {
hasStarted = true;
console.log('timeout started');
$timeout(function () {
console.log('timeout ended');
data = 42;
deferred.resolve(data);
}, 4000);
}
return deferred.promise;
}
});