我有一个指令,可以将日期和时间转换为更好的-人类阅读的形式,例如“现在”,“一分钟前”,..
我想定期更新,因此翻译为“现在”的日期将在一分钟后更新。。
一种解决该问题的方法,使该指令成为$interval
,以便它在60'000ms之后不断更新,但使用此指令可能会导致日期较大的页面出现瓶颈。
第二个想法是提供服务,它将向$rootScope
广播事件心跳,并且指令将绑定侦听器并更新其时间。但这也意味着我将每隔N秒遍历应用程序中所有具有广播事件的范围。.
所以问题。有什么办法,如何使角度服务(更纯净的解决方案更好)将服务仅触发一个指令的事件?
类似:
$directive("timeAgo").$emit("hearthbeat", new Date().getTime())
您可以尝试使用过滤器代替指令。据我所知,AngularJS更新每个$ digest圈子的过滤器。因此,您根本不需要使用计时器。但是我不确定我是否了解过滤器如何正常工作。
关于服务,您可以尝试使用$rootScope.$broadcast
方法代替$rootScope.$emit
。文档说$emit
向上发送事件,而$broadcast
向下发送事件。因此,对于前一个事件,该事件仅可在$rootScope
上访问,而不会传播到其子级。您可以在官方文档中找到有关这些方法的更多信息,例如,in this question。
我认为,也可以使用常规回调代替事件。您可以尝试在服务中添加addTickEvenListener
之类的方法,并在每个计时器滴答时仅调用注册的回调。我不确定,但是在指令销毁时删除事件侦听器可能会有些问题。可能可以通过侦听示波器的$destroy
事件来解决此问题,就像它解释的那样here。
而不是依靠$rootScope
,您可以创建一个总体包装指令,将在要使用智能日期的所有范围内使用一次,就像这样...
app.directive('smartDateMaster', SmartDateMasterDirective);
function SmartDateMasterDirective() {
return {
restrict: 'AE',
scope: true,
controller: 'SmartDateController'
};
}
app.controller('SmartDateController', ['$interval', '$scope', SmartDateCntl]);
function SmartDateCntl($interval, $scope) {
// one interval is set, and the event is broadcast from this scope
$interval(function() {
$scope.$broadcast('sdPulse', new Date());
}, 10000); // 10 seconds, adjust to taste
}
...,然后在任何要显示这些相对聪明的日期之一的地方,都使用一个指令来侦听事件并相应地进行更新:
app.directive('smartDate', SmartDateDirective);
function SmartDateDirective() {
return {
restrict: 'A',
template: '<span>{{ dateText }}</span>',
scope: {
srcDate: '=smartDate' /* a reference to a JS time object */
},
link: function($scope, elem, attrs) {
$scope.$on('sdPulse', function(evt, currentDate) {
var difference = currentDate.getTime() - $scope.srcDate.getTime();
// some logic to determine what the date text should be based on difference
// then set it in scope for display
$scope.dateText = 'whatever you decided';
});
}
};
}
HTML的实现看起来像这样,您用Smart Date Master指令包装了所有出现的Smart Date。任何需要智能日期的地方,都可以使用smart-date
属性以及指向父范围中日期的可分配表达式。
<body>
<!-- some outer content unconcerned with dates -->
<smart-date-master>
<!-- some inner content with dates spread throughout -->
<div>
Jack commented on your status <span smart-date="jackCommentDate"></span>.
</div>
<div>
Jill poked you <span smart-date="jillPokeDate"></span>.
</div>
<div>
John sent you a message <span smart-date="johnMsgDate"></span>
</div>
</smart-date-master>
</body>
这应该仍然是一个高性能的解决方案,您将不会做任何非标准或效率低下的事情。
我创建了一个小插曲来解释一些粗略的想法:http://plnkr.co/edit/d8vE0HCLbemgiPNuvl47?p=preview
It is not complete yet since elements are not moved to different queues after threshold is met.