AngularJS,将更改应用于工厂的视图

AngularJS, apply changes to the view from the factory

本文关键字:工厂 视图 应用于 AngularJS      更新时间:2023-09-26

我尝试显示来自工厂$exceptionHandler有效期为 5 秒的错误消息。所以我有一个带有以下代码的视图

<div class="messages">
    <div class="message" ng-repeat="message in errors">
         {{message}}
    </div>
</div>

和工厂

services.factory('$exceptionHandler',function ($injector) {
    return function(exception, cause) {
        var $rootScope = $injector.get('$rootScope');
        $rootScope.errors = $rootScope.errors || [];
        $rootScope.errors.push(exception.message);
        setTimeout(function(){
            $rootScope.errors.splice(0,1);
        }, 5000);
    };
});

消息显示正常,但在从阵列中删除它们后,它们仍然存在于视图中。我想我需要对$digest和$apply做点什么,但我不明白是什么。需要帮助!

当你

应该使用Angular的$timeout服务时,你正在使用setTimeout

当回调由setTimeout angular 触发时,它不知道它必须刷新 html。如果您改用$timeout那么它将知道在回调完成后进行摘要循环,并且您的页面应该正确更新。

您也可以从回调内部显式触发摘要循环,有时您必须这样做,但对于超时,只需使用提供的服务。