AngularJS:实时更新函数

AngularJS : Update A Function In RealTime

本文关键字:函数 实时更新 AngularJS      更新时间:2023-09-26

我有一个控制器:

$scope.timeAgoCreation = function(order) {
  return moment(order.createdAt).fromNow();
};

从某种角度来看:

{{timeAgoCreation(order)}}

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

有可能使其实时更新吗?

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

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

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

你有工作的jsFiddle。

看看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>

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

如果你正在寻找AngularJS特有的东西,你可能想看看angular timer。

您也可以看看这里的时钟示例,并替换您的momentjs代码,而不仅仅显示日期和时间。

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

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

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