【问题标题】:Resolving a directive inside a linking function在链接函数中解析指令
【发布时间】:2015-05-25 16:11:16
【问题描述】:

我正在尝试构建一种机制,允许我在链接函数中解析指令。

例子:

angular.module('directives', [])

    .directive('myContainer', ['$compile', function ($compile) {
            return {
                restrict: "E",
                replace: true,
                link: function (scope, element, attrs) {
                   angular.forEach(scope.component.components, function(component){

                       var newScope = scope.$new()
                       newScope.component = component;
                       var elem = angular.element('<'+component.type+'>'+'</'+component.type+'>')

                       //Trying to compile directive to be resolved
                       var resolvedDirective = $compile(elem)(scope) 
                       element.append(resolvedDirective)
                  })
                }
            });

问题是,“resolvedDirective”(由 component => 类型定义)只是创建了一个包含另一个指令名称的标签,稍后将解析它。

为了示例,我的机制被简化了(递归...)

希望我的问题已经足够清楚......

提前致谢!

【问题讨论】:

  • 您的示例和行为似乎完全没问题。我想我没有得到这个问题。您可以将其放入 plunker 并通过示例描述您需要的行为吗?
  • 你能稍微澄清一下问题和问题吗?我用你的代码做了一个 jsfiddle,它似乎工作正常。 jsfiddle.net/nyL441c7/3

标签: angularjs angularjs-directive


【解决方案1】:

您的问题需要更清晰。请更新您的指令所需的结果。

您可以遵循此模式。这个答案已经解释了很多关于如何在指令中添加编译指令

Angularjs directive add directives as attribute and bind them dynamically

在您的情况下,您想附加新指令,编译并绑定它。

所以尝试在编译阶段添加你的元素并在postLink阶段使用$compile

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-05
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多