Reputation: 617
I've struggled to find any information on this online, so here goes:
In an angular app, there are several options to include templates. Depending on the use of the application, different methods might prove superior. In my case, I'm writing an application where most pages are going to be viewed every time the application is used.
My current approach is using the $routeProvider
approach with a templateUrl
for each view, which leads to fetching multiple .html files at various stages. This does, in my opinion, put unnecessary load on the webserver.
Is there another option to include the full content in a single request, which conforms to angular best practices?
My current best idea is to include all templates in the index file, and use ng-if
to only display the current relevant view.
Upvotes: 0
Views: 821
Reputation: 8436
It might be worth taking a look at $templateCache, which could be injected into a TemplateService (such as the below); the job of the service being to load whatever files are passed to it. You could inject the service into a top level controller and cache any files you might need later on:
MainCtrl
app.controller('MyMainCtrl', ['TemplateService', function(TemplateService) {
/* Specify templates to be loaded */
var templates = [ '/foo.html', '/bar.html' ];
/* Fetch and cache each template */
_.each(templates, function(template) {
TemplateService.loadTemplate(template)
.done(function() {
console.log('Loaded template: ' + template);
});
});
}]);
TemplateService
app.service('TemplateService', ['$templateCache', function ($templateCache) {
return {
loadTemplate: function(template) {
var deferred = new $.Deferred();
/* Check if the template is already been loaded */
if ($templateCache.get(template)) {
deferred.resolve();
} else {
var options = {
async: false,
type: 'GET',
url: template
};
/* Fetch template */
$.ajax(options)
.done(function (response) {
$templateCache.put(template, response);
deferred.resolve();
})
.fail(function () {
console.log('Unable to load template: ' + template);
deferred.reject();
});
}
return deferred.promise();
}
}
}]);
Upvotes: 1
Reputation: 57
This is a perfectly legitimate way to do it the route provider is there to handle what to load when. When you enter a new route, angular will destroy the old one and load the new one, so it's not like all of your templates are in the DOM at the same time, same goes with ng-if.
If you feel like your application is going to be very large and include a ton of view you can look into lazy loading with angular and something like Requirejs. If you take that route I'd wait a few weeks for Angular 1.4 and the new router they are releasing for it
Upvotes: 0