在内部更改Notification Factory模型后,Angular ng-repeat不会更新

时间:2015-11-19 12:36:49

标签: javascript angularjs angularjs-ng-repeat angular-services

在我的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
}

enter image description here

然而,正在发生的事情是,即使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>

解决此问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:5)

尝试使用angular $ timeout而不是setTimeout。区别在于$ timeout运行摘要周期,这是ng-repeat更新值所必需的。