【问题标题】:Track to see when a view changes in angularjs跟踪以查看 angularjs 中的视图何时更改
【发布时间】:2012-08-02 22:29:45
【问题描述】:

有谁知道当视图改变时如何使角度触发事件?或者在请求和下载视图时?我正在尝试为页面更改添加加载动画。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    看看this thread 看起来$httpProvider.responseInterceptors 是添加这类东西的好地方。

    This fiddle 展示了一个很好的例子,说明在哪里添加代码来启动/停止 ajax 请求的微调器。 This fiddle 类似,但实际上显示和隐藏了一个“正在加载...” div。

    如果您只想在视图更改时显示微调器,您可以将开始/停止代码限制在 content-type 等于 text/html 时,类似于 this postapplication/json 显示的内容。

    注意:在我的测试中,在检索我的 .html 文件时,spinnerFunction 中的 headersGetter()['Content-Type'] 似乎被省略了,而在进行服务调用时它被填充了。

    【讨论】:

    • 完美。正是我需要的。谢谢你:)
    • 这是 1.2 的最新版本吗?
    【解决方案2】:

    我认为更简单、适应性强的方法是使用 AngularJS $http.pendingRequests.length 调用。它返回待处理的 ajax 调用计数。所以当它到达0 时,你的页面就完成了加载。

    您可以创建一个指令,在任何元素上插入一个加载 div(稀松布),然后等待所有 ajax 调用解决,然后删除您的微调器。

    这是制作 AngularJS 指令的代码的核心:

            // Prepend the loading div to the dom element that this directive is applied.
            var scrim = $('<div id="loading"></div>');
            $(scrim).prependTo(domElement);
    
            /**
             * returns the number of active ajax requests (angular + jquery)
             * $.active returns the count of jQuery specific unresolved ajax calls. It becomes 0 if
             * there are no calls to be made or when calls become finished.
             * @return number of active requests.
             */
            function totalActiveAjaxRequests() {
                return ($http.pendingRequests.length + $.active);
            }
    
            /**
             * Check for completion of pending Ajax requests. When they're done,
             * remove the loading screen and show the page data.
             */
            scope.$watch(totalActiveAjaxRequests, function whenActiveAjaxRequestsChange() {
                if(totalActiveAjaxRequests() === 0){
                    $log.log("done loading ajax requests");
                    $(scrim).remove();
                    $(domElement).css("position", "inherit");
                }
            });
    

    请注意,$.active 是无证的。

    【讨论】:

    • 任何时候 :) 我只是在这个问题上敲了几个小时,然后想分享一下。
    • 顺便说一句,您也可以使用$scope.$watch 来达到相同的效果,而无需使用setTimeout。这将是一个更好的选择,因为它与 $scope 摘要一起出现。你也可以使用这个插件,但你必须在完成后手动调用$scope.onReady()github.com/yearofmoo/AngularJS-Scope.onReady
    • 再次感谢 $scope.$watch 的建议。更新了用于指令的代码(这就是作用域不是 $scope 的原因)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多