简体   繁体   English

重新评估AngularJS中计时器的过滤器

[英]Reevaluate filter on timer in AngularJS

I have a filter that I use to display relative time ie 5 mins ago . 我有一个过滤器,用于显示相对时间,即5 mins ago I want to be able to make this filter (or write a directive) to re-evaluate this every minute. 我希望能够使此过滤器(或编写指令)每分钟重新评估一次。 How can I do this? 我怎样才能做到这一点?

JS Filter JS过滤器

m.filter('relativeTime', function () {
    return function (input, showAgo) {
        if (typeof showAgo == "undefined") {
            showAgo = true;
        }

        var dateMoment = input;
        if (typeof input == "string") {
            dateMoment = moment(input);
        }

        return dateMoment.fromNow(showAgo);
    };
});

HTML 的HTML

<span class="relativeTime">{{activity.Time | relativeTime }}</span>

Although it's possible to create a stateful filter, the documentation strongly advices to make only stateless and idempotent filters. 尽管可以创建有状态过滤器,但文档强烈建议仅制作无状态和幂等过滤器。 That's why a directive is a better idea here. 这就是为什么指令在这里是更好的主意的原因。

The principle is simple: when the directive is compiled, create a timer that will refresh the value every minute. 原理很简单:编译指令时,创建一个计时器,该计时器将每分钟刷新一次值。 The $interval service is perfect for that goal. $interval服务非常适合该目标。 However, as stated by the documentation, don't forget to destroy it when you don't need it any more. 但是,如文档所述,不要忘记在不再需要它时将其销毁。

MyApp.directive('relativeTime', function ($interval) {
    return {
        scope: {
            time: '=',
        },
        template: '<div>{{relativeTime}} secondes ago.</div>',
        link: function ($scope) {
            $scope.relativeTime = 0;

            var intervalPromise = $interval(function () {
                ++$scope.relativeTime;
            }, 1000);

            $scope.$watch('time', function (time) {
                var currentTime = new Date();
                $scope.relativeTime = Math.round((currentTime.getTime() - time.getTime()) / 1000);
            });

            $scope.$on('$destroy', function () {
                $interval.cancel(intervalPromise);
            });
        },
    };
});

Fiddle 小提琴

For demonstration purposes, this directive is very simple and updated every second. 出于演示目的,此指令非常简单,并且每秒更新一次。 But it's shouldn't be difficult to adapt it to your use case and in particular to your date.fromNow() function. 但这并不难使它适应您的用例,尤其是您的date.fromNow()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM