Minify HTML Code used by AngularJS - angularjs

In my application, I want to minify not only my javascript code but also html templates in a single javascript file. But I cannot find any examples how to do this.
templates/tmpl1.html
templates/tmpl2.html
controllers/ctrl1.js
controllers/ctrl2.js
-> minify all files to "app.js"
I think HTML code should be converted to strings, because as I know, it's not possible to write HTML into javascript files.

Angular has a template cache that you can directly tamper with.
So you can
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templates/tmpl2.html', '<strong>This is the content of the template</strong>');
});
You can either manually create a .js file that adds all your templates in $templateCache as strings and then combine/minify it together with all your other .js files, or you could (should) use node.js, grunt and grunt-angular-templates and handle all of this automatically.

Related

Where should I use $templateCache?

I want to use $templateCache service to add some html into the cache. In Angular documentation example, it only shows the case of using it in run:
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
However, when I am trying to add some templates through myApp config, there seems to be injector error. Is there a way to use templateCache not in RUN?
Thanks
run is the correct place to use the $templateCache. Since $templateCache is a service, it's not accessible in the configuration phase, because it hasn't been created yet. config is used to configure services (like $templateCache) using their providers. You can only inject providers to config.
My opinion is that, most of the time, you shouldn't be writing code that accesses $templateCache directly at all. What you should be doing is using a build system such as gulp and a plugin such as gulp-angular-templatecache.
Then your templates are simply a bunch of .html files, your editor recognises them as html and does the appropriate linting while you edit, and all you have to do is ensure your app declares a dependency on the template module.
So the code you gave above would become:
var myApp = angular.module('myApp', ['myappTemplates']);
and the use of $templateCache inside .run() is pushed down to automatically generated code that you never see.

Angular templates grunt not loading

I have AngularJS project with more than 20 html templates (routes, modals).
I'm using grunt-angular-templates to split tempaltes in one file templates.js.
In my Angular project I'm using angular-route 1.2.25 for routing.
When I try to use template from templates.js file, browser crashes and not responding. There is any error on console.
The problem is only with html templates with Angular stuff (ng-switch, ng-show etc.)
When I load clean html it works.
I thing the problem is with compile the templates from $templateCache, but how o manage it?
Templates.js
...
$templateCache.put("name","HTML");
...
After long hours of search I found what's wrong.
In my solution I'm using Modal Boostrap for Angular.
grunt-angular-templates plugin don't compile this templates correctly. I just skip this files and all works.

How can I pre load a template in Angular UI router?

I am using Angular UI router. I have many template calls like this:
var access = {
name: 'access',
templateUrl: 'app/access/partials/a1.html',
};
The page served by Access depends on the :content.
Is there a way that I could combine all these HTML files into one and pre-load the files so every action didn't involve another request? I realized I can put my HTML directly inside the template but can I combine the HTML from multiple templates into one file and have it all pre-loaded so it's ready when needed?
Is there a way that I could combine all these HTML files into one and pre-load the files so every action didn't involve another request?
Yes, by using html2js;
or, to be exact, a grunt/gulp plugin called, respectively, grunt-html2js / gulp-html2js
HOW IT WORKS
According to this grunt-html2js tutorial:
" html2js is a plugin (...) that parses all template files in your application and creates a javascript file that populates the $templateCache.
This is very useful trick to reduce the number of request your app needs to make to start the application.
It can also minify the html snippets saving some bandwitdh as well."
----------
According to the grunt-html2s Github repository:
"html2js converts a group of templates to JavaScript and assembles them into an Angular module that primes the cache directly when the module is loaded.
You can concatenate this module with your main application code so that Angular does not need to make any additional server requests to initialize the application."
----------
And according to me :)
What I like about html2js is that you don't need to change any of your angular code, but just configure gruntfile.js / gulpfile.js.
Your templateUrl files will then automagically be available in $templateCache.
So it does exactly what you wished for:
Combine all your templates into a module;
Write the JavaScript source for the module;
All you need to do is to specify the module as a dependency in your code.
Once the module is loaded, all your templates are available in the cache: no request needed!
EXAMPLES OF GRUNT / GULP CONFIG
grunt.initConfig({
html2js: {
options: {
base: 'app',
module: 'templates',
htmlmin: {
... many available options: see GitHub repo ...
}
},
main: {
src: ['app/**/*.html'],
dest: 'templates.js'
},
},
})
then just use the templates module as a dependency:
angular.module('myApp', [ 'templates']);
----------
Here is an example from the gulp-html2js GitHub repository:
gulp.task('scripts', function() {
gulp.src('fixtures/*.html')
.pipe(html2js({
outputModuleName: 'template-test',
useStrict: true
}))
.pipe(concat('template.js'))
.pipe(gulp.dest('./'))
})
TESTING
What's more, html2js is also a very good tool to test directives that use the templateUrl property.
FOR MORE INFORMATION
I came accross html2js after reading Joel Hooks' (Egghead instructor) book about automation, which I strongly recommend.
Watch a dedicated video about html2js in the pro section of the EggHead website.
Testing directives using the templateUrl property with Karma and karma-ng-html2js-preprocessor
NOTE
Technically, you could just use ng-html2js, without using Gulp or Grub; you could then use a command line like the following:
ng-html2js inputFile [outputFile] [-m moduleName] [--module-var ngModule]
However, as you would need to run the above command for each templateUrl file, Gulp/Grub automation seems to be a more efficient way to go.
DISCLAIMER
I have no particular interest or shares in the book/websites/tools I mentioned.
Note: I should also add, you also add this file to your html page:
<script src="path/to/templates.js"></script>
Why not use ng-include in your main html file to load all html's at once.
Something like this...
<div ng-repeat="template in templates">
<ng-include src="template.url"></ng-include>
</div>
So here templates is an array of objects which contains all the url's the other templates which you want to load at once in your main.html file.
Easy. Create them all as ng-template blocks:
<script type="text/ng-template" id="app/access/partials/a1.html">
Content of the template.
</script>
There is already a grunt-angular-templates grunt plugin specific to this angular task only. i have been using it for a while now. this plugin automatically caches your HTML templates using $templateCache in one file which you can add in your application.
grunt-angular-templates - https://www.npmjs.com/package/grunt-angular-templates
Use,
yourApp.run(['$templateCache', function($templateCache) {
$templateCache.removeAll();
}])
Your problem pointed in this site too,
http://javahow.net/questions/27321315/using-angulars-ui-router-how-can-we-make-sure-the-new-version-of-the-html-part

How to dynamically include all template partials when using a module in AngularJS

I have several modules that require some template partials to be loaded whenever the module is used. I am storing these files in a folder called partials inside each module subfolder. My starting point for my app is meanjs, and I am storing partials file are in public/modules//partials/*.html.
I have seen several ng-include and directive examples, but being new to AngularJS each sample I read confuses me further as to what is best practice / most AngularJS appropriate way to do this.
Store your partials whenever you wants.
To load them all use angular template cache.
Use Grunt or gulp to generate automatically. Personally I use gulp.
Here is my working example of one of my project.
install nodejs and npm
npm intall gulp -g
npm install gulp-angular-templatecache
create gulpfile.js
var templateCache = require('gulp-angular-templatecache'),
watch = require('gulp-watch');
gulp.task('generate', function () {
gulp.src('public/*/partials/*.html')
.pipe(templateCache('templates.js', {module: 'YOURMODULENAME', standalone: false}))
.pipe(gulp.dest('public/js'));
});
gulp.task('watch-partials', function () {
gulp.watch('public/*/partials/*.html', ['generate']);
});
then use it like this:
gulp generate - to regenerate partials
gulp watch-partials - watch file changes, if partials are changed it automatically run generate task for you. :)
One more thing, dont forget to include template.js in your html file
<script src="public/js/template.js"></script>
Every time you change your partial dont forget to regenerate your template cache.
You should take advantage of $templateCache. In your partials folder define the templates like this:
angular.module('yourTemplateModule', []).run('$templateCache', function ($templateCache) {
$templateCache.put('yourTemplate', '<div>...some HTML here...</div>');
}
Then create a module, named for example 'app.tpls', which has as dependencies all your template modules. Inject it as dependency to your main app module, probably located in meanjs and now you have your templates ready whenever you need them in your application. You retrieve them by calling:
$templateCache.get('yourTemplate');

Have gulp to update references to angular views

I have an angular application which I am using gulp to build.
To keep my app code organized, I like to keep my directory structure grouped together by modules:
app
-> modules
-> sample
- sample.js
- sample.html
app.js
So, in my angular app/modules/sample.js I reference the template
templateUrl: 'modules/sample/sample.html
I would like to keep this structure, but in my distribution, I would like my html moved to a views folder. I have a gulp task which does this
gulp.task('views', function () {
return gulp.src('app/modules/**/*.html')
.pipe(gulp.dest('dist/views'))
.pipe($.size());
});
However, this obviously breaks the references inside my javascript code. How would I use gulp to update the reference to 'views/sample/sample.html' in the javascript for distribution?
You could use gulp-replace to change the path in your JS files once you've compiled them for production. Pretty simple to use:
.pipe($.replace('app/modules/', 'dist/views/modules/'))

Resources