在我的 Angular 应用程序中,我有一个简单的通知工厂,它允许我存储和获取我想传达给用户的信息:
(function() {
'use strict';
angular
.module('peaches')
.factory('NotificationFactory', factory);
// factory.$inject = ['dependencies'];
/* @ngInject */
function factory() {
var messages = [];
var service = {
postAlert: postAlert,
getAlerts: getAlerts,
deleteAlert: deleteAlert
};
return service;
function postAlert(alert) {
messages.push(alert);
if (alert.duration) {
setTimeout(function() {
deleteAlert(alert);
}, alert.duration)
}
}
function getAlerts() {
return messages;
}
function deleteAlert(alert) {
messages.splice(messages.indexOf(alert), 1);
}
}
})();
正如您在 postAlert
中看到的那样功能,我希望能够删除通知,如果所述通知有 duration
属性(property),在duration
之后毫秒数。
目的是让某些类型的通知在数秒后自动消失,而不是要求交互关闭。
这是一个示例通知:
var reportSaved = {
msg: "Report saved.",
type: "success",
duration: 1500
}
但是,即使 setTimeout
发生了什么正在按预期工作并有效删除设置 duration
之后的通知,该元素仍然被绘制,直到我更改页面(之后它按预期消失),所以 ng-repeat
在调用 deleteAlert
后永远不会更新来 self 的工厂。
这是 HTML:
<div class="notification" ng-repeat="alert in vm.alerts(); track by $index" ng-cloak>
<i ng-if="alert.type === 'notification'" class="fa fa-spinner"></i><i ng-if="alert.type === 'success'" class="fa fa-check-circle"></i> {{alert.msg}}
</div>
解决这个问题的最佳方法是什么?
最佳答案
尝试使用 Angular $timeout 而不是 setTimeout。不同之处在于 $timeout 运行摘要循环,这是 ng-repeat 更新值所必需的。
关于javascript - 通知工厂模型内部更改后,Angular ng-repeat 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33804175/