AngularJS:实时更新函数
AngularJS : Update A Function In RealTime
我有一个控制器:
$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>
相关文章:
- 标记的实时更新,无需加载页面谷歌地图API V3
- 参数更改时,角度表达式中的函数不更新
- 使用Ajax调用在服务器上实时更新页面
- 实时更新,无需刷新页面
- Dojo dGrid/dStore实时更新
- 如何在页面上进行实时更新
- 从JSON实时更新
- 我希望我的php/html网站上的JavaScript能够实时更新
- 使用php-js-msyql的实时更新消息系统
- 实时更新的持久连接
- Node js redis socket.io pubsub实时更新
- 从子函数执行父函数;t更新父级'的属性
- 在OpenCart中,我们如何实时更新数据
- Instagram实时更新没有回应
- 将多个输入值传递给函数以更新图像
- 将多个选择值传递给函数以更新图像
- 在react组件中使用ajax获取实时更新的数据
- 如何使用highchart在yii中添加实时更新图表
- 函数调用后,角度示波器未在屏幕上实时更新
- AngularJS:实时更新函数