Angular ngRoute 无法使用 ngInclude 重新加载

Angular ngRoute not working on reload with ngInclude

以防其他人遇到同样的问题。虽然对某些人来说微不足道,但对我来说却并非微不足道。

问题:

当页面加载时,当在 ng-include 中使用 ng-view 时,ngRoute 无法加载 shell(着陆页)模板。

但是,如果我们开始在页面中导航(包括导航回登录页面),那么模板加载会很好。就好像第一次加载页面时,它完全跳过加载着陆模板。

设置:

index.html 的 body 底部某处:

<script src="angular-route.js"></script>

index.html 模板中的某处

<div ng-include="'root-shell.html'"></div>

root-shell.html 模板中的某处

<div ng-view></div>

JS:

(function (/* IIFE enclosed code*/) {

    angular('myApp', [$routeProvider]);

    angular('myApp').config(function($routeProvider){

        $routeProvider
            .when('/', {
                templateUrl: 'root-shell.html',
                controller: 'RootShellController', // optional
                controllerAs: 'rootShellCtrl' // optional
            }).
            .when('/about', {
                templateUrl: 'about.html',
                controller: 'AboutController', // optional
                controllerAs: 'aboutCtrl' // optional
            }).
            otherwise({
                redirectTo: '/'
            });
    });

})(/* IIFE invoke*/);

为什么会出现问题?

Because if ng-view instantiation is delayed (through ng-include) then the $route instantiation is delayed as well. This means that $route will miss the location change event.

修正:

强制重新加载 $route 服务。

angular('myApp').run(['$route', function($route)  {
    $route.reload();
}]);

为什么有效?

因为angular的执行顺序:

  1. 应用配置
  2. 应用运行
  3. 指令设置
  4. 指令编译
  5. 应用控制器
  6. 指令link
  7. ** 调用的数据解析 **
  8. 新航线的控制器

和运行块:

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

免责声明:

我是 Angular 的新手,因此如果我误解了 and/or 错误地表达了一个概念,那么一定要插话。