0

Let's say I have a boolean format that controls how a collection of items should be displayed by my directive. Depending on the value of format, my html changes radically.

So far I'm using two separate templates, and I dynamically recompile the directive whenever format changes, by using $watch(format) in the link function of the directive.

I wonder if it would be faster to use only one template, and split all my code between a big ng-show="format" and a ng-hide="format". What's the best practice in that situation?

2
  • use ng-if, it removes the dom elements Commented Feb 17, 2015 at 3:49
  • It's not removing elements that I'm worried about it, but the time it takes to recreate them. Commented Feb 19, 2015 at 20:22

1 Answer 1

1

$compile is expensive (relatively). Your use case sounds like a candidate for ng-switch, so don't reinvent the wheel if ng-switch works for you.

However, inside your directive, you can cache the compilation of each template and then re-link them by calling the link function returned by $compile. This would be pretty much as performant as ng-switch .

In pseudo code your link function would look like:

link: function(scope, element, attrs) {
     //create and cache your template link functions
     var format1link = $compile(template1);
     var format2link = $compile(template2);
     scope.$watch('format') {

         //call appropriate link function based on the value of format
         var newElement = format1link(scope);
         //or
         var newElement = format2link(scope);

         //replace element contents with newElement

     });
}
Sign up to request clarification or add additional context in comments.

3 Comments

Neat! I was caching the html templates, but I didn't thought of caching the compiled templates themselves.
But you are right: ng-switch is much easier in that case. Otherwise I had to handle the asynchronous generation of the compiled templates, as well as the $watch listener, so it was a pain. And ng-switch seems really fast so far.
Glad to help. 9 times out of 10 angular already does what you are trying to do!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.