Angularjs中指令模板函数有什么好处?

时间:2014-01-06 01:30:28

标签: javascript angularjs templates compilation directive

根据文档,template可以是一个函数,它接受两个参数elementattributes,并返回表示模板的字符串值。它用HTML的内容替换当前元素。替换过程将所有属性和类从旧元素迁移到新元素。

compile函数处理转换模板DOM。它需要三个参数,elementattributestransclude函数。不推荐使用transclude参数。它返回link函数。

似乎templatecompile函数非常相似,可以实现相同的功能。 template函数定义模板,compile函数修改模板DOM。但是,它可以在template函数本身中完成。我无法理解为什么在template函数之外修改模板DOM。反之亦然,如果可以在compile函数中修改DOM,那么template函数的需求是什么?

2 个答案:

答案 0 :(得分:50)

编译功能可用于在结果模板函数绑定到范围之前更改DOM。

考虑以下示例:

<div my-directive></div>

您可以使用compile函数更改模板DOM,如下所示:

app.directive('myDirective', function(){
  return {

    // Compile function acts on template DOM
    // This happens before it is bound to the scope, so that is why no scope
    // is injected
    compile: function(tElem, tAttrs){

      // This will change the markup before it is passed to the link function
      // and the "another-directive" directive will also be processed by Angular
      tElem.append('<div another-directive></div>');

      // Link function acts on instance, not on template and is passed the scope
      // to generate a dynamic view
      return function(scope, iElem, iAttrs){

        // When trying to add the same markup here, Angular will no longer
        // process the "another-directive" directive since the compilation is
        // already done and we're merely linking with the scope here
        iElem.append('<div another-directive></div>');
      }
    }
  }
});

因此,如果您的指令需要,您可以使用compile函数将模板DOM更改为您喜欢的任何内容。

在大多数情况下,tElemiElem将是相同的DOM元素,但如果指令克隆模板以删除多个副本,有时它可能会有所不同(参见ngRepeat

在幕后,Angular使用双向渲染过程(编译+链接)来删除已编译的DOM片段的副本,以防止Angular不得不一遍又一遍地处理(=解析指令)相同的DOM对于每个实例,如果该指令标记出多个克隆,从而产生更好的性能。

希望有所帮助!


评论后添加:

templatecompile函数之间的差异:

模板功能

{
    template: function(tElem, tAttrs){

        // Generate string content that will be used by the template
        // function to replace the innerHTML with or replace the
        // complete markup with in case of 'replace:true'
        return 'string to use as template';
    }
}

编译功能

{
    compile: function(tElem, tAttrs){

        // Manipulate DOM of the element yourself
        // and return linking function
        return linkFn(){};
    }
}

在调用compile函数之前调用模板函数。

虽然它们可以执行几乎相同的东西并共享相同的“签名”,但关键的区别在于模板函数的返回值将替换指令的内容(如果replace: true,则替换完整的指令标记) ,编译函数应该以编程方式更改DOM并返回链接函数(或具有前后链接功能的对象)。

从这个意义上说,如果只需要用字符串值替换内容,就可以将模板函数视为某种便利函数,而不必使用编译函数。

希望有所帮助!

答案 1 :(得分:6)

模板功能的最佳用途之一是有条件地生成模板。这允许您基于属性或任何其他条件自动创建模板。

我见过一些非常大的模板,它们使用ng-if来隐藏模板的各个部分。但是,不是将所有内容放入模板并使用ng-if,这可能导致过度绑定,您可以从模板函数的输出中删除不会被使用的DOM部分。

假设您有一个指令,其中包含子指令item-firstitem-second。并且子指令永远不会改变外部指令的生命周期。在调用编译函数之前,您可以调整模板的输出。

<my-item data-type="first"></my-item>
<my-item data-type="second"></my-item>

这些的模板字符串是:

<div>
  <item-first></item-first>
</div>

<div>
  <item-second></item-second>
</div>

我同意这是一个极端简化,但我有一些非常复杂的指令,外部指令需要根据类型显示一个,大约20个不同的内部指令。我可以在外部指令上设置类型,并让模板函数使用正确的内部指令生成正确的模板,而不是使用transclude。

然后将格式正确的模板字符串传递给编译函数等

相关问题