Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically refresh filters

Tags:

angularjs

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!

like image 379
doorman Avatar asked Mar 23 '13 16:03

doorman


1 Answers

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.

like image 63
Stewie Avatar answered Oct 19 '22 22:10

Stewie