AngularJs:具有模板属性功能的指令。如何获得范围值?

时间:2015-07-26 19:47:17

标签: angularjs angularjs-directive

我尝试使用不同的指令模板。我发现的所有解决方案都是在链接器函数中使用 $ compile service

但是我们的指令工厂的template属性可以是一个函数。为什么不使用这个选项?

所以:

return {
  template: function(element, attr) {
    if(attr.template){
      return attr.template;
    }
    return defaultTemplate;
  }
}

之后在html中:

<my-directive template="button.template"></my-directive>

像魅力一样工作。 只缺少一件事:我不知道如何在其中获取范围变量button.template。现在只需获取&#39; button.template&#39;像一个字符串。也尝试使用括号 - 相同的字符串仅使用括号&#39; {{button.template}}&#39;。是否有可能或者我应该返回使用编译服务的解决方案?

1 个答案:

答案 0 :(得分:2)

{<1}}函数在链接阶段之前执行。这意味着在评估范围时,范围尚未可用(这就是它未被注入函数的原因)。

模式是将template注入指令工厂并在$compile阶段使用它,因为此时,范围 已经可用。例如,

postLink