Is there a way to preload templates when using AngularJS routing?
This is an addition to the answer by @gargc.
If you don't want to use the script tag to specify your template, and want to load templates from files, you can do something like this:
myApp.run(function ($templateCache, $http) { $http.get('Template1.html', { cache: $templateCache }); }); myApp.config(function ($locationProvider, $routeProvider) { $routeProvider.when('/p1', { templateUrl: 'Template1.html' }) });
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'
)
I think I have a slightly improved solution to this problem based on Raman Savitski's approach, but it loads the templates selectively. It actually allows for the original syntax that was asked for like this:
$routeProvider.when('/p1', { controller: controller1, templateUrl: 'Template1.html', preload: true })
This allows you to just decorate your route and not have to worry about updating another preloading configuration somewhere else.
Here is the code that runs on start:
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 }); } } } })]);