AngularJS,从工厂申请更改视图 [英] AngularJS, apply changes to the view from the factory

查看:71
本文介绍了AngularJS,从工厂申请更改视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用一​​个5秒的寿命,以显示从$ exceptionHandler的工厂的错误消息。所以,我有以下code视图

I try to display error messages from $exceptionHandler factory with a lifespan of 5 seconds. So I have a view with the following code

<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);
    };
});

该消息被显示正常,但是从数组删除它们后,它们仍然是美元视点P $ psent。我想我需要做$消化和$适用的东西,但我不明白。需要帮助!

The messages were displayed fine, but after removing them from array, they are still present on view. I think I need to do something with $digest and $apply, but I don't understand what. Need help!

推荐答案

您正在使用的setTimeout 时,你应该使用角的 $超时服务。

You are using setTimeout when you should be using angular's $timeout service.

在回调是由的setTimeout 触发角不知道它有刷新的HTML。如果你使用 $超时,而不是那么它会知道rtun一个消化循环回调完成后,你的页面应该更新正确。

When the callback is triggered by setTimeout angular doesn't know that it has to refresh the html. If you use $timeout instead then it will know to rtun a digest loop after the callback has completed and your page should update correctly.

您也可以明确地从回调内部引发消化循环,有时你必须这样做,但对于超时只使用所提供的服务。

You could also explicitly trigger the digest loop from inside the callback, sometimes you have to do that, but for timeouts just use the service provided.

这篇关于AngularJS,从工厂申请更改视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆