【问题标题】:Insert directive dynamically and compiling动态插入指令并编译
【发布时间】:2014-09-25 03:57:56
【问题描述】:

我有一个场景,当用户点击一个链接时,我想在 DOM 中插入一个自定义元素,例如

    //user clicks    
    $scope.click = function () {
          var el = $compile("<my-directive></my-directive>")($scope);
          $element.after(el);
     };

my-directive.. 指令有一个 html 模板.. 比如说 (template1.html)

<p>My Template for my-directive</p>
{{SomeProperty}}

my-directive 是这样定义的

module.directive('myDirective', ['$compile', function ($compile) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: '/template1.html',
        scope: true
    };
}]);

如果我们假设 myDirective 中的范围在运行此代码后实际上具有 SomeProperty 的值,我确实会将 my-directive 插入 DOM 并替换为模板 - template1.html 但是 {{SomeProperty}} 没有完全被替换了!我该怎么做??

详情请见Plunkr

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您在 Plunkr 中使用了 $compile("&lt;my-directive&gt;&lt;/my-directive&gt;")($scope.$parent);。删除.$parent

    将模板更改为:

    <p>My Template for my-directive</p>
    {{d.SomeProperty}}
    

    正如你所做的d in data

    然后就可以了 :)

    【讨论】:

      【解决方案2】:

      我不确定您是否有任何其他错误,但我发现删除 replace:true 使其对我有用。

      我不确定这里到底发生了什么,但不知何故,你将指令添加到 dom 的交互 + 立即替换它会导致它不起作用。

      我注意到的另一件事是,通过使用$element.after(el);,您最终会得到一个超出控制器范围的元素。控制器的范围不在 div 中。不幸的是,我只在我的 plunkr 中看到了这个,所以不知道这是否也影响了你。

      Plunkr here

      【讨论】:

      猜你喜欢
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 2016-06-06
      • 2017-09-24
      相关资源
      最近更新 更多