Sn0opr Sn0opr - 1 year ago 70
AngularJS Question

Cache compiled template of an AngularJS directive

I have a directive with a template that has many ngRepeat and take some time to render and I'm ok with it. But the problem is that I'm calling this directive more than one time in the same view. So it's causing a lot freeze and performance issue because of the ngRepeat that occurs for each instance of the directive.

The template is the same for every instance of the directive, so it would be great if I can compile it only at first time, cache the compiled html and use it for another directive instances.

Answer Source

This is my solution, it's dirty but it's working fine.

What I did is loading the template synchronously with XMLHttpRequest in the directive function and then compile it in the controller of the directive only one time.

.directive('myDirective', function($compile) {
     var cachedTemplate = null,
         templateCompiled = false;
    var xhr = new XMLHttpRequest();
    //Do an asynchronous request to wait until we load the template'GET', 'directives/template.html', false);
    if (xhr.status == 200) {
        cachedTemplate = xhr.responseText;
    return {
        restrict: 'E'
        scope: {
        date: 'someData'
    controller: function($scope, $element, $attrs) {
        if (!templateCompiled) {
          //we compile the template only one time.
            cachedTemplate = $compile(cachedTemplate)($scope);
            templateCompiled = true
        //We replace/include the compiled template in our $element
        ///... do the job....

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download