Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : Update A Function In RealTime

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 ?

like image 785
Alex Avatar asked Jul 14 '13 16:07

Alex


3 Answers

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.

like image 77
PrimosK Avatar answered Oct 01 '22 20:10

PrimosK


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>
like image 42
Maxim Shoustin Avatar answered Oct 01 '22 22:10

Maxim Shoustin


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.

like image 27
Matt Johnson-Pint Avatar answered Oct 01 '22 21:10

Matt Johnson-Pint