Re-evaluating a timer filter in AngularJS

I have a filter that I use to display relative time, i.e. 5 mins ago . I want to be able to make this filter (or write a directive) to re-evaluate it every minute. How can i do this?

Js filter

 m.filter('relativeTime', function () { return function (input, showAgo) { if (typeof showAgo == "undefined") { showAgo = true; } var dateMoment = input; if (typeof input == "string") { dateMoment = moment(input); } return dateMoment.fromNow(showAgo); }; }); 

HTML

 <span class="relativeTime">{{activity.Time | relativeTime }}</span> 
+5
source share
1 answer

Although you can create a stateful filter, the documentation strongly advises that you create only stateless and idempotent filters. That is why the directive is the best idea here.

The principle is simple: when the command is compiled, create a timer that will update the value every minute. The $interval great for this purpose. However, as indicated in the documentation, be sure to destroy it when you no longer need it.

 MyApp.directive('relativeTime', function ($interval) { return { scope: { time: '=', }, template: '<div>{{relativeTime}} secondes ago.</div>', link: function ($scope) { $scope.relativeTime = 0; var intervalPromise = $interval(function () { ++$scope.relativeTime; }, 1000); $scope.$watch('time', function (time) { var currentTime = new Date(); $scope.relativeTime = Math.round((currentTime.getTime() - time.getTime()) / 1000); }); $scope.$on('$destroy', function () { $interval.cancel(intervalPromise); }); }, }; }); 

Fiddle

For demonstration purposes, this directive is very simple and is updated every second. But it’s easy to adapt it to your use case and, in particular, to your date.fromNow() function.

+4
source

All Articles