Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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   }) 
like image 374
andersh Avatar asked Sep 10 '13 09:09

andersh


People also ask

How does AngularJS routing work?

Routing in AngularJS is used when the user wants to navigate to different pages in an application but still wants it to be a single page application. AngularJS routes enable the user to create different URLs for different content in an application.

Is AngularJS a template engine?

AngularJS is client-side template rendering while Express is server-side.

What are templates in AngularJS?

In AngularJS, templates are written with HTML that contains AngularJS-specific elements and attributes. AngularJS combines the template with information from the model and controller to render the dynamic view that a user sees in the browser.


2 Answers

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' })     }); 
like image 124
andersh Avatar answered Oct 13 '22 23:10

andersh


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')

like image 36
garst Avatar answered Oct 13 '22 21:10

garst