【问题标题】:Which function is called each time url changes in AngularJS?每次 AngularJS 中的 url 更改时调用哪个函数?
【发布时间】:2026-01-14 01:45:01
【问题描述】:

我必须同时发生所有请求的队列,而无需等待 angularjs 中上一个请求的响应。
我有一个加载函数,每次更改 url 路由时都会显示加载 div,但它不行在该函数中创建一个队列。

谁能告诉我每次更改 url 路由时在 angularjs 路由中调用哪个函数?
这里是路由代码:

angular.module('myApp', ['myApp.directives', 'myApp.services', 'myApp.filters']).config(
    function($routeProvider, $locationProvider, $httpProvider) {
        $locationProvider.html5Mode(false);
        $locationProvider.hashPrefix('!');

        $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

        var loading = function (data, headersGetter) {
            $('loadingDiv').show();
            return data;
        };
        $httpProvider.defaults.transformRequest.push(loading);

        $routeProvider.
        when('/', {
            templateUrl: 'elements/home/home.html',
            controller: homeCtrl
        });
   });

【问题讨论】:

    标签: angularjs angularjs-routing


    【解决方案1】:

    你可以使用类似的东西:

    .run( function($rootScope, $location) {
       $rootScope.$watch(function() { 
          return $location.path(); 
        },
        function(a){  
          console.log('url has changed: ' + a);
          // show loading div, etc...
        });
    });
    

    【讨论】:

    • 但是 $scope 没有在路由中定义。
    • 你是对的,我已经在 Module.run() 初始化函数中编辑了答案,$rootScope
    • 谢谢..它可以工作,但现在我想要路由或控制器中任何地方的所有待处理请求的列表..你有什么想法吗?
    【解决方案2】:

    $route 服务有一系列事件,您可以在控制器中使用 $.on 进行监控:

    $rootScope.$on("$routeChangeStart", function(args){})
    
    $rootScope.$on("$routeChangeSuccess"....
    
    $rootScope.$on("$routeChangeError"....
    

    见文档$route

    您可以在元素上设置ng-show 而不是使用jQuery,并在$routeChangeStart 回调中将变量设置为true,在$routeChangeSuccess 回调中设置为false。

    这些事件的一个很好的演示:https://github.com/johnlindquist/angular-resolve

    【讨论】: