ng-html2js takes .html templates and converts them into strings stored in AngularJS's template cache. This allows you to bundle all of your templates into a single JavaScript file for simpler deployment and faster loading.
1. Install grunt.
2. Install grunt-html2js:
npm install grunt-html2js --save-dev
3. One the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
grunt.loadNpmTasks('grunt-html2js');
4. Using grunt-contrib-watch to moniter all tpl.html files in pulbic folder and register the html2js:main to the watcher.
/** * Created by Answer1215 on 3/15/2015. */ module.exports = function(grunt) { grunt.initConfig({ watch: { files: ["server/**/*.js", 'public/**/*.tpl.html'], tasks: ['browserify', 'html2js:main'] }, html2js: { options: { base: 'public', module: 'app.templates', /*Create a new module called app.tempaltes*/ singleModule: true, /*For all templates just create a single module*/ useStrict: true, htmlmin: { collapseBooleanAttributes: true, collapseWhitespace: true, removeAttributeQuotes: true, removeComments: true, removeEmptyAttributes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true } }, main: { src: ['public/**/*.tpl.html'], dest: 'build/templates.js' } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-html2js'); }
So, once your tpl files has been changed, grunt task will run and create template js file.
5. Include your template.js to the index.html:
<script src="../build/templates.js"></script>
6. Inject the app.template module:
angular.module("app", ["ui.router", 'app.templates']) .config(function config($stateProvider) { $stateProvider.state("answer", { url: "", views: { 'home@': { templateUrl: "home/home.tpl.html" }, 'visit@': { templateUrl: "visit/visit.tpl.html" } } }) });
7. Test code:
<!-- index.html --> <!DOCTYPE html> <html ng-app="app"> <head> <title>Egghead.io Tutorials</title> <link rel="shortcut icon" href="favicon.ico"> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.11/angular-ui-router.js"></script> <script src="../build/templates.js"></script> <script src="ap.js"></script> </head> <body> <section ui-view="home"></section> <nav ui-view="visit"></nav> </body> </html>
<!-- home/home.tpl.html --> <h1>Hello World, Grunt-html2js!!</h1>
<!-- visit/visit.tpl.html --> <h2>Visit!</h2>
build/template.js:
angular.module('app.templates', []).run(['$templateCache', function($templateCache) { "use strict"; $templateCache.put("home/home.tpl.html", "<h1>Hello World, Grunt-html2js!!</h1>"); $templateCache.put("visit/visit.tpl.html", "<h2>Visit!</h2>"); }]);
More:
https://egghead.io/lessons/angularjs-using-ng-html2js-to-convert-templates-into-javascript