Search code examples
angularjsofflineangularjs-routing

Is there a way to preload templates when using AngularJS routing?


After the Angular app is loaded I need some of the templates to be available offline.

Something like this would be ideal:

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

Solution

  • There is a template cache service: $templateCache which can be used to preload templates in a javascript module.

    For example, taken from the docs:

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

    There is even a grunt task to pre-generate a javascript module from html files: grunt-angular-templates

    Another way, perhaps less flexible, is using inline templates, for example, having a script tag like this in your index.html:

    <script type="text/ng-template" id="templates/Template1.html">template content</script>
    

    means that the template can be addressed later in the same way as a real url in your route configuration (templateUrl: 'templates/Template1.html')