Angular 通知工厂模型内部更改后 ng-repeat 未更新

Angular ng-repeat not updating after Notification Factory model changed internally

在我的 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 数字之后有 duration 属性,我希望能够删除该通知毫秒。

目的是让某些类型的通知在数秒后自动消失,而不是要求交互关闭。

这是一个示例通知:

var reportSaved = {
    msg: "Report saved.",
    type: "success",
    duration: 1500
}

但是,尽管 setTimeout 按预期工作并在设置 duration 之后有效地删除了通知,但该元素仍然会被绘制,直到我更改页面(之后它按预期消失),因此 ng-repeat 在我的工厂内调用 deleteAlert 后永远不会更新。

这是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 更新值所需要的。