Rather than relying on $rootScope
, you can create an over-arching wrapper directive that you will use once around all scopes that you want to use smart dates, like this...
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
}
... and then anywhere you want to show one of these smart, relative dates, use a directive that listens for the event and updates accordingly:
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';
});
}
};
}
Implementation in HTML would look something like this, where you wrap all occurrences of Smart Dates with the Smart Date Master directive. Anywhere you want a Smart Date, use the smart-date
attribute along with an assignable expression that points to a date in the parent scope.
<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>
This should still be a performant solution, and you wouldn't be doing anything non-standard or wildly inefficient.