Reused promise

This shows that promises can be reused, so if you want to expose an API for deferred loading you simply keep track of a single deferred.

by Jeremy Likness

HTML

<script src="https://code.angularjs.org/1.3.9/angular.min.js"></script>
<div ng-app="myApp">
    <ul>
        <li ng-if="!list1.length">Loading...</li>
        <li ng-repeat="tick in list1">{{tick}}</li></ul>
    <ul><li ng-if="!list2.length">Loading...</li>
        <li ng-repeat="tick in list2">{{tick}}</li>
    </ul>
</div>

JavaScript

(function (app) {
    
    function DelayedService($q) {
        var _this = this;
        this.defer = $q.defer();
        setTimeout(function () {
            _this.defer.resolve([1,2,3]);
        }, 1000);
        this.getList = function () {
            return _this.defer.promise;
        };
    }
    
    app.service('delayedService', DelayedService);
    
    app.run(['$rootScope', 'delayedService', function (rs, ds) {
        ds.getList().then(function (list) {
            rs.list1 = list;
        });
        setTimeout(function () {
            ds.getList().then(function (list) {
                rs.list2 = list;
            });
        }, 2000);
    }]);
})(angular.module('myApp', []));