Angular ngRoute无法使用ngInclude重新加载

时间:2016-02-03 14:32:29

标签: angularjs routes ngroute angularjs-ng-include

如果其他人遇到同样的问题。虽然对一些人来说微不足道,但这对我来说并非微不足道。

问题:

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

但是,如果我们开始浏览页面,包括导航回登录页面,那么模板加载就好了。这就好像第一次页面加载它完全跳过加载着陆模板。

设置:

index.html身体底部的某处:

<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*/);

1 个答案:

答案 0 :(得分:0)

为什么会出现这个问题?

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

为什么会有效?

由于角度的执行顺序:

  1. app config
  2. app run
  3. 指令设置
  4. 指令编译
  5. app controller
  6. 指令链接
  7. **数据解析名为**
  8. 新路线的控制器
  9. 和运行块:

    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很新,因此,如果我误解和/或歪曲了一个概念,那么无论如何都要插入。