angularjsangularjs-ng-repeatangular-directiveangular-cache

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.


Solution

  • 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
        xhr.open('GET', 'directives/template.html', false);
        xhr.send(null);
    
        if (xhr.status == 200) {
            cachedTemplate = xhr.responseText;
        }
    
        return {
            restrict: 'E'
            scope: {
            date: 'someData'
        }
    
        controller: function($scope, $element, $attrs) {
            if (!templateCompiled) {
              // compile the template only one time.
                cachedTemplate = $compile(cachedTemplate)($scope);
                templateCompiled = true
            }
    
            // replace/include the compiled template in our $element
            $element.replaceWith(cachedTemplate);
            // ... do the job....
        }
    }