<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="App" ng-controller="ctrl">
    <h1>Stateful cached filter</h1>
    Github user <input ng-model="username">
    <br>
    full name {{username | details:'name'}}
    blog {{username | details:'blog'}}
    <br>
    <img ng-src="{{username | details:'avatar_url'}}" width="100" height="100" >
    <br>
    <button ng-click="forceDigestCycle()">Force digest</button>
    <script src="https://rawgit.com/bahmutov/console-log-div/master/console-log-div.js"></script>
  </body>

</html>
angular.module('App', [])
  .filter('details', function ($http) {
    var cached = {};
    var githubApiUrl = 'https://api.github.com/users/';
    function detailsFilter(input, field) {
      console.log('details for github user', input, field);
      if (input) {
        if (input in cached) {
          // avoid returning a promise!
          return typeof cached[input].then !== 'function' ? 
            cached[input][field] : undefined;
        } else {
          cached[input] = $http({
            method: 'GET',
            url: githubApiUrl + input
          }).success(function (info) {
              cached[input] = info;
              console.log('generated result for', info);
            });
        }
      }
    }
    detailsFilter.$stateful = true;
    return detailsFilter;
  })
  .controller('ctrl', function ($scope) {
    $scope.username = 'bahmutov';
  });


/* Styles go here */