I have in a controller:
$scope.timeAgoCreation = function(order) {
return moment(order.createdAt).fromNow();
};
And in a view:
{{timeAgoCreation(order)}}
It return the correct value: 9 minutes ago. But this value is not updated in realtime. I have to refresh the page.
Is it possible to make it update realtime ?
Just add this function in to the controller (don't forget to inject $timeout
service):
function fireDigestEverySecond() {
$timeout(fireDigestEverySecond , 1000);
};
fireDigestEverySecond();
$timeout
automatically fires digest cycle after function passed in as first parameter is called so the value in view should be updated every second.
There you have working jsFiddle.
Take a look on this example in Fiddle
It clearly demonstrates current date form with update each second.
JS
function Ctrl2($scope,$timeout) {
$scope.format = 'M/d/yy h:mm:ss a';
}
angular.module('time', [])
// Register the 'myCurrentTime' directive factory method.
// We inject $timeout and dateFilter service since the factory method is DI.
.directive('myCurrentTime', function($timeout, dateFilter) {
// return the directive link function. (compile function not needed)
return function(scope, element, attrs) {
var format, // date format
timeoutId; // timeoutId, so that we can cancel the time updates
// used to update the UI
function updateTime() {
element.text(dateFilter(new Date(), format));
}
// watch the expression, and update the UI on change.
scope.$watch(attrs.myCurrentTime, function(value) {
format = value;
updateTime();
});
// schedule update in one second
function updateLater() {
// save the timeoutId for canceling
timeoutId = $timeout(function() {
updateTime(); // update DOM
updateLater(); // schedule another update
}, 1000);
}
// listen on DOM destroy (removal) event, and cancel the next UI update
// to prevent updating time ofter the DOM element was removed.
element.bind('$destroy', function() {
$timeout.cancel(timeoutId);
});
updateLater(); // kick off the UI update process.
}
});
HTML
<div ng-app="time">
<div ng-controller="Ctrl2">
Date format: <input ng-model="format"> <hr/>
Current time is: <span my-current-time="format"></span>
</div>
</div>
You'll need some kind of timer to call the function periodically.
If you're looking for something specific to AngularJS, you might want to take a look at angular-timer.
You could also look at the ticking clock example here and substitute your momentjs code instead of just showing the date and time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With