0

I have an AngularJS app that displays duration like such "2 minutes ago" based on a timestamp data.

How do I update this in real-time? Short of using windows.setInterval, I wonder if it can be done more "angular-ly"

Disclaimer: I am newbie in AngularJS

Seamus
  • 4,539
  • 2
  • 32
  • 42
pixelfreak
  • 17,714
  • 12
  • 90
  • 109
  • Try this: http://stackoverflow.com/questions/18006334/updating-time-ago-values-in-angularjs-and-momentjs – uksz Apr 09 '15 at 07:42
  • 2
    there is a Angularjs Service called [`$interval`](https://docs.angularjs.org/api/ng/service/$interval). This Service does all the angular `$digest` and/or `$apply`. That means its the angular way of intervals – Nano Apr 09 '15 at 07:49
  • example usage is var stop = $interval(function(){ do something },8000) // 8 seconds If I were you I would save the interval pointer so I could delete it at a later stage, like so $interval.cancel(stop); – Chris Noring Apr 09 '15 at 07:55

1 Answers1

0

The most Angular-ly thing to do is create a directive:

app.directive("minutesAgo", function($interval) {
  var MINUTE = 60000;
  function updateMinutes(scope) {
    scope.minutes = Math.floor((Date.now() - new Date(scope.startTime)) / MINUTE);
    scope.pluralizedMinutes = scope.minutes < 1 ? "Less than a minute" :
                              scope.minutes +
                              (scope.minutes == 1 ? " minute" : " minutes");
  }

  return {
    restrict: "AE",
    scope: {
      startTime: "="
    },
    template: "<span>{{pluralizedMinutes}} ago</span>",
    link: function(scope, element) {
      updateMinutes(scope);
      $interval(function() {
        updateMinutes(scope);
      }, MINUTE);
    }
  };
})

This can be used inside an element with a controller that specifies a timestamp like so:

<minutes-ago start-time="timestamp"></minutes-ago>

You can try it out on Plunker.

Austin Mullins
  • 7,307
  • 2
  • 33
  • 48