190

I have a route setup like this:

var myApp = angular.module('myApp', []).
    config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
        when('/landing', {
            templateUrl: '/landing-partial',
            controller: landingController
        }).
        when('/:wkspId/query', {
            templateUrl: '/query-partial',
            controller: queryController
        }).
        otherwise({
            redirectTo: '/landing'
        });
}]);

I want to be able to make angularjs download both the partials in the beginning and not when requested.

Is it possible?

8 Answers 8

270

Yes, there are at least 2 solutions for this:

  1. Use the script directive (http://docs.angularjs.org/api/ng.directive:script) to put your partials in the initially loaded HTML
  2. You could also fill in $templateCache (http://docs.angularjs.org/api/ng.$templateCache) from JavaScript if needed (possibly based on result of $http call)

If you would like to use method (2) to fill in $templateCache you can do it like this:

$templateCache.put('second.html', '<b>Second</b> template');

Of course the templates content could come from a $http call:

$http.get('third.html', {cache:$templateCache});

Here is the plunker those techniques: http://plnkr.co/edit/J6Y2dc?p=preview

9
  • 2
    Thanks for the reply. I like the template cache Idea because I do not want to put things into a script tag. How to use it? Documentation is bad. I saw the fiddle in one of the comments there. But I want to load from a url. Sep 11, 2012 at 6:54
  • Updated the answer based on the comments Sep 11, 2012 at 10:27
  • 4
    I sometimes use the inline <script> tag together with server-side includes. This lets me keep my partials as separate files for organizational purposes, but still delivers everything in one document. Oct 27, 2014 at 18:57
  • 2
    Do you know if there's a speed boost in choosing one solution vs another?
    – Atav32
    Jan 12, 2015 at 21:49
  • 2
    I am caching templates using http call, but the the problem is the name of the cached template would be the url forexample: $http.get('app/correction/templates/group-correction-table.html', {cache:$templateCache}); and then whenever I want to load the template I have to use this ugly name :( which I don't like, Like this: <td ng-include="'app/correction/templates/group-correction-table.html'">
    – Shilan
    Dec 2, 2015 at 12:14
25

If you use Grunt to build your project, there is a plugin that will automatically assemble your partials into an Angular module that primes $templateCache. You can concatenate this module with the rest of your code and load everything from one file on startup.

https://npmjs.org/package/grunt-html2js

2
  • 11
    There's also grunt-angular-templates which does the same kind of thing - npmjs.org/package/grunt-angular-templates - works a treat Oct 29, 2013 at 5:02
  • Does this also work for templates on the index file? I have an ng-view and ng-include in my index file and I'm having trouble getting my application to show up.
    – Batman
    Oct 19, 2014 at 9:47
16

Add a build task to concatenate and register your html partials in the Angular $templateCache. (This answer is a more detailed variant of karlgold's answer.)

For grunt, use grunt-angular-templates. For gulp, use gulp-angular-templatecache.

Below are config/code snippets to illustrate.

gruntfile.js Example:

ngtemplates: {
  app: {                
    src: ['app/partials/**.html', 'app/views/**.html'],
    dest: 'app/scripts/templates.js'
  },
  options: {
    module: 'myModule'
  }
}

gulpfile.js Example:

var templateCache = require('gulp-angular-templatecache');
var paths = ['app/partials/.html', 'app/views/.html'];

gulp.task('createTemplateCache', function () {
return gulp.src(paths)
    .pipe(templateCache('templates.js', { module: 'myModule', root:'app/views'}))
    .pipe(gulp.dest('app/scripts'));
    });

templates.js (this file is autogenerated by the build task)

$templateCache.put('app/views/main.html', "<div class=\"main\">\r"...

index.html

<script src="app/scripts/templates.js"></script>
<div ng-include ng-controller="main as vm" src="'app/views/main.html'"></div>
3
  • 2
    Hi @james I am using this gulp plugin. All .html load properly but when I try to specify html as part of some dialog box plugin (I am using ng-material) it throws 404. ex - $mdDialog.show({ controller: 'entityGridCtrl', templateUrl: 'user/partials/entityGrid.html' });
    – Anand
    Apr 1, 2015 at 19:34
  • Did you replace my app/views references with your user/partials? Apr 1, 2015 at 19:42
  • Thx. I am not changing path of partials, I posted my question - stackoverflow.com/questions/29399453/…
    – Anand
    Apr 1, 2015 at 19:46
11

If you wrap each template in a script tag, eg:

<script id="about.html" type="text/ng-template">
<div>
    <h3>About</h3>
    This is the About page
    Its cool!
</div>
</script>

Concatenate all templates into 1 big file. If using Visual Studio 2013, download Web essentials - it adds a right click menu to create an HTML Bundle.

Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works: Vojta Jina's Gist

Its the $http.get that should be changed to use your bundle file:

allTplPromise = $http.get('templates/templateBundle.min.html').then(

Your routes templateUrl should look like this:

        $routeProvider.when(
            "/about", {
                controller: "",
                templateUrl: "about.html"
            }
        );
2

If you use rails, you can use the asset pipeline to compile and shove all your haml/erb templates into a template module which can be appended to your application.js file. Checkout http://minhajuddin.com/2013/04/28/angularjs-templates-and-rails-with-eager-loading

0

I just use eco to do the job for me. eco is supported by Sprockets by default. It's a shorthand for Embedded Coffeescript which takes a eco file and compile into a Javascript template file, and the file will be treated like any other js files you have in your assets folder.

All you need to do is to create a template with extension .jst.eco and write some html code in there, and rails will automatically compile and serve the file with the assets pipeline, and the way to access the template is really easy: JST['path/to/file']({var: value}); where path/to/file is based on the logical path, so if you have file in /assets/javascript/path/file.jst.eco, you can access the template at JST['path/file']()

To make it work with angularjs, you can pass it into the template attribute instead of templateDir, and it will start working magically!

1
  • I'm not sure this answers the question, and changing the programming language is probably overkill.
    – xdhmoore
    Jan 28, 2014 at 20:21
0

You can pass $state to your controller and then when the page loads and calls the getter in the controller you call $state.go('index') or whatever partial you want to load. Done.

-1

Another method is to use HTML5's Application Cache to download all files once and keep them in the browser's cache. The above link contains much more information. The following information is from the article:

Change your <html> tag to include a manifest attribute:

<html manifest="http://www.example.com/example.mf">

A manifest file must be served with the mime-type text/cache-manifest.

A simple manifest looks something like this:

CACHE MANIFEST
index.html
stylesheet.css
images/logo.png
scripts/main.js
http://cdn.example.com/scripts/main.js

Once an application is offline it remains cached until one of the following happens:

  1. The user clears their browser's data storage for your site.
  2. The manifest file is modified. Note: updating a file listed in the manifest doesn't mean the browser will re-cache that resource. The manifest file itself must be altered.
2
  • 1
    unfortunately this feature is deprecated now developer.mozilla.org/en-US/docs/Web/HTML/… so just a heads up, use this approach at your own risk
    – Lazy Coder
    Feb 2, 2016 at 17:24
  • According to the HTML standard, "This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.)" The suggested replacement, Service Workers, is still an "Experimental technology" as of early 2016. For now, I am still using the Application Cache because it works well for my applications. Feb 2, 2016 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.