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

Angular performance: ng-show vs. dynamically recompile directive

假设我有一个布尔值 format 来控制我的指令应如何显示项目集合。根据 format 的值,我的 html 发生了根本性的变化。

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

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

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

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

在伪代码中,您的 link 函数如下所示:

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

     });
}