【问题标题】:AngularJs: Directive with function for template property. How to get scope value?AngularJs:具有模板属性功能的指令。如何获得范围值?
【发布时间】:2015-07-26 19:47:16
【问题描述】:

我正在尝试使用不同的指令模板。我发现的所有解决方案都是关于在链接器函数中使用 $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。现在只是像字符串一样获取'button.template'。还尝试使用括号 - 仅使用括号“{{button.template}}”的相同字符串。是否有可能或者我应该返回到带有编译服务的解决方案?

【问题讨论】:

  • 我认为这不起作用,因为在评估 {{button.template}} 之前调用了您的模板函数。我想这只是您的指令的简化示例,否则您可以使用ng-include
  • 是的,你是对的,它是简化版。但是你能告诉我更多关于你对 ng-include 的想法吗?你打算如何将范围变量中的模板放在那里?

标签: angularjs angularjs-directive


【解决方案1】:

template 函数在链接阶段之前执行。这意味着作用域在被评估时还不可用(这就是它没有被注入到函数中的原因)。

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

app.directive('myDirective', [ '$compile',
    function ($compile) {
        function postLink(scope, element, attrs) {
            // Here, both the DOM and the scope are available, so
            // you can extend the DOM with templates compiled against the scope

            // if you are using <my-directive template="button.template"></my-directive>
            var template = scope.$eval(attrs.template);

            // if you are using <my-directive template="{{ button.template }}"></my-directive>
            var template = attrs.template;  // interpolation is already processed against the scope

            // compile the template and append to existing DOM
            element.append($compile(template || defaultTemplate)(scope));
        }

        function template(element, attrs) {
            // Here, you cannot evaluate attrs.template against the scope
            // because the scope does not yet exist! Only the DOM is
            // available (you can use the raw values of attributes if needed)
            return '<div></div>';
        }

        return {
            template: template,
            link: postLink
        }
    }
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多