angularjs - 可以在定义路由之前填充 $templateCache 吗?

标签 angularjs angular-routing

我不想延迟加载我的路线模板。相反,我想在执行任何路由之前将所有路由模板加载到 $templateCache 中。

这就是我正在做的事情:

angular.module('myApp', ['ngRoute']).config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider)
{
    $locationProvider.html5Mode(false);

    $routeProvider.when("/main", {templateUrl: "main", controller: "MainCtrl"})
                  .when("/login",{templateUrl: "login", controller: "LoginCtrl"});
}])
.run(['$location','$templateCache', function ($location, $templateCache)
{
   //...Save templates in $templateCache
   $location.path("/login");
}]);

如果您浏览到 /,这可以正常工作因为它不匹配任何路线。但是如果你浏览或刷新 /#/login在我的运行 block 开始运行并向服务器发出请求之前,路由服务似乎尝试加载模板。

无论如何确保填充 $templateCache 的代码将在路由服务查找模板之前执行?

最佳答案

如果你使用 grunt 你我强烈推荐 grunt-angular-templates为此目的,但是如果您不想并且想要手动创建单独的模块,在该模块中您的逻辑与您现在所拥有的类似,则大致如下:

angular.module('myapp.templates').run(['$templateCache', function($templateCache) {
$templateCache.put(...

然后简单地将该模块引用为您的应用程序依赖项。依赖模块的运行 block 将在路由逻辑启动之前首先运行,这就是您想要的。

关于angularjs - 可以在定义路由之前填充 $templateCache 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19644191/

相关文章:

Angular:通过链接参数数组传递路由数据

javascript - 单击时 AngularJS 在 Controller 中更改部分

angularjs - 使用过滤器为 mousestats 标记敏感数据

javascript - 我必须绕过 ngModelController.$parsers 来存储值

angularjs - 如何向 AngularUI 日历添加图标

javascript - 重新加载页面时,生产 URL 中的 Angular 2 会被破坏

javascript - 从 ngView 访问链接功能?

javascript - 如何在我的应用程序中显示 html 数据?

angularjs - Angular2 教程(英雄之旅): Cannot find module './app-routing.module'

angular - 使用 Cypress 测试 Angular 时如何防止整页重新加载?