5

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 ?

4

4 回答 4

10

只需将此功能添加到控制器中(不要忘记注入$timeout服务):

function fireDigestEverySecond() {
    $timeout(fireDigestEverySecond , 1000);
};
fireDigestEverySecond();

$timeout在作为第一个参数传入的函数被调用后自动触发摘要循环,因此视图中的值应该每秒更新一次。

在那里你有工作jsFiddle

于 2013-07-14T16:52:15.940 回答
3

看一下Fiddle中的这个例子

它清楚地展示了每秒更新的当前日期形式。

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>
于 2013-07-14T17:41:18.777 回答
1

您需要某种计时器来定期调用该函数。

如果你正在寻找特定于 AngularJS 的东西,你可能想看看angular-timer

您还可以查看此处的时钟示例并替换您的 momentjs 代码,而不仅仅是显示日期和时间。

于 2013-07-14T16:43:28.813 回答
0

我只是在寻找一种使用 Moment.js 做同样事情的方法,并通过 urish 找到了 angular-moment 模块

它具有自定义 Angular 指令,因此您需要的所有代码都是一个属性,例如:

<span am-time-ago="message.time"></span>
于 2015-06-10T02:05:29.530 回答