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.
Brian genisio
source share