<!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>
    More details after 1 second about <input ng-model="something">: {{something | details}}
    <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 ($timeout) {
    var cached = {};
    function detailsFilter(input) {
      console.log('details for', input);
      if (input) {
        if (input in cached) {
          // avoid returning a promise!
          return typeof cached[input] === 'string' ? cached[input] : undefined;
        } else {
          cached[input] = $timeout(function () {
            cached[input] = input + input;
            console.log('generated result for', input);
          }, 1000);
        }
      }
    }
    detailsFilter.$stateful = true;
    return detailsFilter;
  })
  .controller('ctrl', function ($scope) {
    $scope.something = 'foo';
  });


/* Styles go here */