I am using a filter to display the time ago since something was added:
angular.module('filters').('fromNow', function () {
return function (date) {
return moment(date).fromNow();
}
});
How can I automatically trigger the filter for every minute such that the time ago will get refreshed. Can I e.g. use $timeout inside the filter to achieve this?
Thanks!
As a matter of fact, your feature has actually already been pretty closely described on Angular Docs.
For these kind of things you'd want to use the directives. You might choose to keep your filtering logic inside you filter function or you may place the whole "time ago" logic inside the directive. Whichever way you want.
JS:
app.filter('fromNow', function () {
return function (date) {
return moment(date).fromNow();
};
});
app.directive('time',
[
'$timeout',
'$filter',
function($timeout, $filter) {
return function(scope, element, attrs) {
var time = attrs.time;
var intervalLength = 1000 * 10; // 10 seconds
var filter = $filter('fromNow');
function updateTime() {
element.text(filter(time));
}
function updateLater() {
timeoutId = $timeout(function() {
updateTime();
updateLater();
}, intervalLength);
}
element.bind('$destroy', function() {
$timeout.cancel(timeoutId);
});
updateTime();
updateLater();
};
}
]
);
HTML:
<div ng-controller="AppController">
Time: <span time="2013-03-23 21:56"></span>
</div>
Plunker
Again, if you take a look at Directive Docs you'll find that this solution is almost a complete ripoff of a directive example found on that page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With