2

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Sn0opr
  • 1,016
  • 2
  • 12
  • 38

1 Answers1

0

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....
    }
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
Sn0opr
  • 1,016
  • 2
  • 12
  • 38
  • You have a race condition here, where the Ajax call may not return in time before the controller function is called. EDIT: nevermind, I noticed that you make a synchronous call - which addresses the race condition but would cause your browser to freeze. – New Dev Dec 17 '14 at 09:32