<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
    <h2>Aborting $http requests</h2>
    <div ng-controller="myCtrl">
      Click here to launch a new request: 
      <button ng-click="GetData()">
        Get Data
      </button>
      <ul>
        <li ng-repeat="request in requests">
            Click here to cancel it <button ng-click="cancel(request)">Cancel</button>
        </li>
      </ul>
      <ul>
        <li ng-repeat="person in people">{{person.name}}</li>
      </ul>
    </div>
  </body>
</html>
var app = angular.module('myApp', []);
app.controller("myCtrl", function($scope, dataFactory) {

  $scope.people = [];
  $scope.requests = [];
  $scope.id = 1;

  $scope.GetData = function() {
    var request = dataFactory.getById($scope.id++);
    $scope.requests.push(request);
    request.promise.then(function(result) {
      $scope.people.push(result);
      clearRequest(request);
    }, function(reason) {
      console.log(reason);
    });
  };

  $scope.cancel = function(request) {
    request.cancel("User cancelled");
    clearRequest(request);
  };

  var clearRequest = function(request) {
    $scope.requests.splice($scope.requests.indexOf(request), 1);
  };
});

app.factory("dataFactory", function($http, $q) {

  var getById = function(id) {
    var canceller = $q.defer();

    var cancel = function(reason) {
      canceller.resolve(reason);
    };

    var promise =
      $http.get("http://swapi.co/api/people/" + id, {
        timeout: canceller.promise
      })
      .then(function(response) {
        return response.data;
      });

    return {
      promise: promise,
      cancel: cancel
    };
  };

  return {
    getById: getById
  };

});
/* Styles go here */