Javascript AngularJS:实时更新函数

Javascript AngularJS:实时更新函数,javascript,jquery,angularjs,momentjs,Javascript,Jquery,Angularjs,Momentjs,我有一个控制器: $scope.timeAgoCreation = function(order) { return moment(order.createdAt).fromNow(); }; 从某种角度来看: {{timeAgoCreation(order)}} 它返回正确的值:9分钟前。但该值不会实时更新。我必须刷新页面 是否可以使其实时更新?您需要某种计时器来定期调用该函数 如果您正在寻找AngularJS特有的东西,您可能想看看 您还可以查看滴答作响的时钟示例,并替换moment

我有一个控制器:

$scope.timeAgoCreation = function(order) {
  return moment(order.createdAt).fromNow();
};
从某种角度来看:

{{timeAgoCreation(order)}}
它返回正确的值:9分钟前。但该值不会实时更新。我必须刷新页面


是否可以使其实时更新?

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

如果您正在寻找AngularJS特有的东西,您可能想看看


您还可以查看滴答作响的时钟示例,并替换momentjs代码,而不只是显示日期和时间。

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

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


您的工作已经完成。

请在中查看此示例

它清楚地显示了当前的日期表,并每秒钟更新一次

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>

日期格式:
当前时间为:
我只是想用Moment.js和urish找到的方法做同样的事情

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

<span am-time-ago="message.time"></span>


这对我很有帮助。。简单的解决方案。。我觉得这应该是答案哇。这是simpe。是的,这应该是答案。
<span am-time-ago="message.time"></span>