Angular.js - apply filter using interval

I use my own angular.js filter for datetime objects:

function relativeTimeFilter() { return function (dateObj) { return getRelativeDateTimeString(dateObj); }; } function getRelativeDateTimeString(dt) { if(!dt) return "undefined ago"; var delta = dt.getSeconds(); if (delta < 0) return "not yet"; if (delta < 1 * 60) return delta == 1 ? "one second ago" : delta + " seconds ago"; if (delta < 2 * 60) return "a minute ago"; if (delta < 45 * 60) return Math.floor(delta/60) + " minutes ago"; if (delta < 90 * 60) return "an hour ago"; if (delta < 24 * (60*60)) return Math.floor(delta/60/60) + " hours ago"; if (delta < 48 * (60*60)) return "yesterday"; if (delta < 30 * (24 * (60*60))) return Math.floor(delta/60/60/24) + " days ago"; if (delta < 12 * (30 * (24 * (60*60)))) { var months = Math.floor(delta/60/60/24/30); return (months <= 1) ? "one month ago" : (months + " months ago"); } else { var years = Math.floor(delta/60/60/24/365); return (years <= 1) ? "one year ago" : (years + " years ago"); } } module.filter("relativetime", relativeTimeFilter); 

At this moment it is not so important which filter I use (I think). The filter receives a Datetime object. A relative temporary application is valid for only one second. The value of one second ago should be updated in a second to 2 seconds ago , etc.

When I apply a filter, this happens only once. So how can I run a filter at a regular interval?

I tried the following:

 setInterval(function() {$scope.$apply()}, 1000) // placed in controller function 

... without success.

Any ideas?

+7
javascript angularjs time setinterval
source share
2 answers

I don’t think you can achieve this with a filter. The reason $scope.$apply() does not work because it is monitoring data changes. Since the data has not actually changed, the filter will never be called again.

Instead, you need to configure the data that is viewed in your controller. Use $timeout instead of setInterval because it is built into the digestive life cycle.

I would consider using a directive for this.

 app.directive('relativeTime', function($timeout) { function update(scope, element) { element.text(getRelativeDateTimeString(scope.actualTime)); $timeout(function() { update(scope, element); }, 1000); } return { scope: { actualTime: '=relativeTime' }, link: function(scope, element) { update(scope, element); } }; }); 

So you can use the following directive:

 <div relative-time="theDate"></div> 

Also, I found a flaw in your getRelativeDateTimeString function. You need to adjust the delta from the current time. getSeconds just gives you seconds of a given time:

 var delta = parseInt(((new Date().getTime()) - dt.getTime()) / 1000); 

This is where CodePen works.

+7
source share

Below is the working jsfiddle directive for updating time, I think you are looking for similar code.

http://jsfiddle.net/vishalvasani/xRg3j/

he uses

 $timeout 
+2
source share

All Articles