2

I would like to have AngularJS filter timeAgo that should be applied for a timestamp to show time passed from timestamp. That's an easy one:

filter('timeago', function() {
  return function(input) {
    return Date.now() - input;
  }
});

But when I wanted to make it LIVE(when user on the page - we update the value each second/each digest) it appeared to be not that easy. We don't change input value, so filter is not recalculated. Is it possible to make it recalculable each second without adding extra parameters?

Fiddle example.

  • I'm not looking for ready libraries (like angular-moment). It's more interesting for me how to implement such concept in AngularJs.
2
  • Can you explain why u want to make such filter not a directive? Are there any other example of usage? Commented Feb 10, 2017 at 10:42
  • it should do the same as angular-moment amTimeAgo filter Commented Feb 10, 2017 at 11:30

1 Answer 1

1

It happens because the filters are now stateless, to make it work for this filter you will need to do:

function timeagoFilter(input) {
  return Date.now() - input;
}

timeagoFilter.$stateful = true;

return timeagoFilter;

but personally I'd turn it into a directive and change the value with plain javascript - if it's just for display purposes - since it's easy to mess up digest cycle and make the app performance degrade

Sign up to request clarification or add additional context in comments.

5 Comments

great! that's what I was looking for
this filter wont work if your digest takes more than ~1ms. Actually it ends with $rootScope:infdig error.
@PetrAveryanov I think you did something wrong if you got infinite digest error
no it is quite obvious 1st digest filter return i.e.10. Second digest - 11. Third 12. Etc. Values are never same. >> error
You might be confusing few things and what digest does

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.