有没有办法在使用AngularJS路由时预加载模板?

and*_*rsh 43 offline angularjs angularjs-routing

加载Angular应用程序后,我需要一些离线可用的模板.

这样的事情是理想的:

$routeProvider
  .when('/p1', {
    controller: controller1,
    templateUrl: 'Template1.html',
    preload: true
  })
Run Code Online (Sandbox Code Playgroud)

and*_*rsh 54

这是@gargc对答案的补充.

如果您不想使用脚本标记指定模板,并且想要从文件加载模板,则可以执行以下操作:

    myApp.run(function ($templateCache, $http) {
        $http.get('Template1.html', { cache: $templateCache });
    });

    myApp.config(function ($locationProvider, $routeProvider) {
        $routeProvider.when('/p1', { templateUrl: 'Template1.html' })
    });
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一下,`$ http.get('Template1.html',{cache:$ templateCache});`应该具有相同的效果.虽然,它并没有太大的区别:) (8认同)
  • 我更喜欢这个解决方案,因为它不需要从HTML模板构建JavaScript文件. (2认同)

gar*_*rst 43

有一个模板缓存服务:$ templateCache,可用于在javascript模块中预加载模板.

例如,取自文档:

var myApp = angular.module('myApp', []);
  myApp.run(function($templateCache) {
  $templateCache.put('templateId.html', 'This is the content of the template');
});
Run Code Online (Sandbox Code Playgroud)

从html文件预生成javascript模块甚至还有一项艰巨的任务:grunt-angular-templates

另一种可能不太灵活的方法是使用内联模板,例如,在index.html中使用这样的脚本标记:

<script type="text/ng-template" id="templates/Template1.html">template content</script>
Run Code Online (Sandbox Code Playgroud)

表示模板可以稍后以与路由配置中的真实URL相同的方式进行寻址(templateUrl: 'templates/Template1.html')

  • 如果您的模板需要从URL获取:`myApp.run(function($ templateRequest){$ templateRequest('/ url/to/template.html',true);});` (13认同)

Tho*_*eck 27

基于Raman Savitski的方法,我认为我对这个问题有一个稍微改进的解决方案,但它有选择地加载模板.它实际上允许这样要求的原始语法:

$routeProvider.when('/p1', { controller: controller1, templateUrl: 'Template1.html', preload: true })

这允许您只是装饰您的路线,而不必担心在其他地方更新另一个预加载配置.

这是在开始时运行的代码:

angular.module('MyApp', []).run([
    '$route', '$templateCache', '$http', (function ($route, $templateCache, $http) {
        var url;
        for (var i in $route.routes) {
            if ($route.routes[i].preload) {
                if (url = $route.routes[i].templateUrl) {
                    $http.get(url, { cache: $templateCache });
                }
            }
        }
    })
]);
Run Code Online (Sandbox Code Playgroud)

  • 如果有一个明确的`preload:false`,我会稍微改变它,只是不预加载,所以默认情况下为路由启用预加载.但我认为决定是个人品味,取决于你想做什么.除了那个伟大的片段!+1 (4认同)

Ram*_*ski 18

预加载模块路由中定义的所有模板.

angular.module('MyApp', [])
.run(function ($templateCache, $route, $http) {
    var url;
    for(var i in $route.routes)
    {
      if (url = $route.routes[i].templateUrl)
      {
        $http.get(url, {cache: $templateCache});
      }
    }
})
Run Code Online (Sandbox Code Playgroud)