角度性能:ng-show与动态重新编译指令

时间:2015-02-17 03:33:21

标签: angularjs angularjs-directive

我想说我有一个布尔format来控制我的指令应该如何显示项目集合。根据{{​​1}}的值,我的html会发生根本变化。

到目前为止,我使用了两个单独的模板,并且每当format发生更改时,我都会通过在指令的link函数中使用format来动态重新编译指令。

我想知道只使用一个模板会更快,并将我的所有代码拆分为大$watch(format)ng-show="format"。那种情况下的最佳做法是什么?

1 个答案:

答案 0 :(得分:1)

$ compile很贵(相对而言)。您的用例听起来像ng-switch的候选者,所以如果ng-switch适合您,请不要重新发明轮子。

但是,在你的指令中,你可以缓存每个模板的编译,然后通过调用$ compile返回的链接函数重新链接它们。这与ng-switch几乎一样。

在伪代码中,您的链接功能如下所示:

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

     });
}