gpt4 book ai didi

javascript - Angular.js - 使用间隔应用过滤器

转载 作者:数据小太阳 更新时间:2023-10-29 04:37:05 25 4
gpt4 key购买 nike

我正在为日期时间对象使用自定义的 angular.js 过滤器:

function relativeTimeFilter()
{
return function (dateObj) {
return getRelativeDateTimeString(dateObj);
};
}

function getRelativeDateTimeString(dt)
{
if(!dt) return "undefined ago";

var delta = dt.getSeconds();
if (delta < 0) return "not yet";
if (delta < 1 * 60) return delta == 1 ? "one second ago" : delta + " seconds ago";
if (delta < 2 * 60) return "a minute ago";
if (delta < 45 * 60) return Math.floor(delta/60) + " minutes ago";
if (delta < 90 * 60) return "an hour ago";
if (delta < 24 * (60*60)) return Math.floor(delta/60/60) + " hours ago";
if (delta < 48 * (60*60)) return "yesterday";
if (delta < 30 * (24 * (60*60))) return Math.floor(delta/60/60/24) + " days ago";
if (delta < 12 * (30 * (24 * (60*60))))
{
var months = Math.floor(delta/60/60/24/30);
return (months <= 1) ? "one month ago" : (months + " months ago");
}
else
{
var years = Math.floor(delta/60/60/24/365);
return (years <= 1) ? "one year ago" : (years + " years ago");
}
}

module.filter("relativetime", relativeTimeFilter);

在这一点上,我使用哪个过滤器并不那么重要(我认为)。过滤器接收一个 Datetime 对象。相对时间声明仅在一秒内有效。意思是 one second ago 必须在一秒后更新到 2 seconds ago 等等。

当我应用过滤器时,这只会发生一次。那么如何定期触发过滤设备呢?

我尝试了以下方法:

setInterval(function() {$scope.$apply()}, 1000) // placed in controller function

...没有成功。

有什么想法吗?

最佳答案

我认为您无法通过过滤器实现这一目标。 $scope.$apply() 不起作用的原因是它正在监视数据的变化。由于数据实际上并没有改变,过滤器再也不会被调用。

相反,您需要调整在 Controller 中查看的数据。使用 $timeout 而不是 setInterval 因为它内置在消化生命周期中。

我会考虑使用指令来执行此操作。

app.directive('relativeTime', function($timeout) {

function update(scope, element) {
element.text(getRelativeDateTimeString(scope.actualTime));
$timeout(function() { update(scope, element); }, 1000);
}

return {
scope: {
actualTime: '=relativeTime'
},
link: function(scope, element) {
update(scope, element);
}
};
});

所以你可以像这样使用指令:

<div relative-time="theDate"></div>

此外,我发现您的 getRelativeDateTimeString 函数存在缺陷。您需要根据当前时间来计算增量。 getSeconds 只为您提供给定时间的秒数:

var delta = parseInt(((new Date().getTime()) - dt.getTime()) / 1000);

这是一个有效的 CodePen .

关于javascript - Angular.js - 使用间隔应用过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18570121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com