<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@1.2.22" data-semver="1.2.22" src="https://code.angularjs.org/1.2.22/angular.js"></script>
    <script data-require="underscore.js@1.6.0" data-semver="1.6.0" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="AppCtrl">
    <h1>Cancelling pending requests</h1>
    <input name="count" ng-model="count" type="text">
    <input name="link" ng-model="link" type="text">
    <button ng-click="addRequests()">Add x requests</button>
    <button ng-click="cancelAll()">Cancel all requests</button>
    <ul>
      <li ng-repeat="req in requests">
        {{req.url}}
      </li>
    </ul>
    
  </body>

</html>
angular.module('app', [])
// This service keeps track of pending requests
.service('pendingRequests', function() {
  var pending = [];
  this.get = function() {
    return pending;
  };
  this.add = function(request) {
    pending.push(request);
  };
  this.remove = function(request) {
    pending = _.filter(pending, function(p) {
      return p.url !== request;
    });
  };
  this.cancelAll = function() {
    angular.forEach(pending, function(p) {
      p.canceller.resolve();
    });
    pending.length = 0;
  };
})
// This service wraps $http to make sure pending requests are tracked 
.service('httpService', ['$http', '$q', 'pendingRequests', function($http, $q, pendingRequests) {
  this.get = function(url) {
    var canceller = $q.defer();
    pendingRequests.add({
      url: url,
      canceller: canceller
    });
    //Request gets cancelled if the timeout-promise is resolved
    var requestPromise = $http.get(url, { timeout: canceller.promise });
    //Once a request has failed or succeeded, remove it from the pending list
    requestPromise.finally(function() {
      pendingRequests.remove(url);
    });
    return requestPromise;
  }
}])
// The controller just helps generate requests and keep a visual track of pending ones
.controller('AppCtrl', ['$scope', 'httpService', 'pendingRequests', function($scope, httpService, pendingRequests) {
  $scope.requests = [];
  $scope.link ="http://google.de";
  $scope.count=10;
  $scope.$watch(function() {
    return pendingRequests.get();
  }, function(pending) {
    $scope.requests = pending;
  })
  
  var counter = 1;
  var counter2 = 2;
  
  $scope.addRequests = function() {
    for (var i = 0, l = $scope.count; i < l; i++) {
         httpService.get($scope.link+'/?req=' + counter2++);
    }
  };
  $scope.cancelAll = function() {
    pendingRequests.cancelAll();
  }
}]);
/* Styles go here */