antoine
antoine

Reputation: 2106

Angular performance: ng-show vs. dynamically recompile directive

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?

Upvotes: 0

Views: 184

Answers (1)

Joe Enzminger
Joe Enzminger

Reputation: 11190

$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

     });
}

Upvotes: 1

Related Questions