i have filter use display relative time i.e. 5 mins ago. want able make filter (or write directive) re-evaluate every minute. how can 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>
although it's possible create stateful filter, documentation strongly advices make stateless , idempotent filters. that's why directive better idea here.
the principle simple: when directive compiled, create timer refresh value every minute. $interval service perfect goal. however, stated documentation, don't forget destroy when don't need more.
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); }); }, }; }); for demonstration purposes, directive simple , updated every second. it's shouldn't difficult adapt use case , in particular date.fromnow() function.
Comments
Post a Comment