Angular Directive – TimeAgo


Timeago directive and filter for Angular with MomentJS

1
<span timeago="{{someDate}}" />

or as a filter

1
<span>{{someDate | timeago}}</span>

For regular date functions, you can use the existing date filter.

The full code is only a few lines of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
app.filter('timeago', function(){
  return function(date){
    return moment(date).fromNow();
  };
});
app.directive('timeago', function() {
  return {
    restrict:'A',
    link: function(scope, element, attrs){
      attrs.$observe("timeago", function(){
        element.text(moment(attrs.timeago).fromNow());
      });
    }
  };
});

So why use a directive over a filter? The filter will run if the digest runs, but a directive can force a digest with $timeout. So the main reason is so you can have this update in real time, you’d only need to add a $timeout() and setInterval(). I didn’t do that here, but it’d be pretty easy to add.

Thanks to Jonathan Rowny

Happy Coding 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s