【问题标题】:Unable to compile a dynamically added Directive into a page无法将动态添加的指令编译到页面中
【发布时间】:2016-07-29 13:47:04
【问题描述】:

我正在尝试将动态添加的元素指令添加到页面中,但它不起作用并在添加的页面中进行编译。这是plunker代码。代码有什么问题?

http://plnkr.co/edit/BFPxAvEahT1I930mvB5r

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script>
        var app = angular.module('myApp', []);
      app.controller("fCtrl",function($scope,$compile){
        $scope.xx = ['x','c','y','z','a'];
        $scope.add = function(){
          var templ = document.getElementById('test').innerHTML;
          templ = templ+'<datan-type content="test1" con="{{xx}}"></datan-type>';
          document.getElementById('test').innerHTML = templ;
          //$compile(document.getElementById('test').innerHTML)($scope);
          alert(document.getElementById('test').innerHTML);
        }
      });

      app.directive('datanType', function ($compile) {
  return { 
    restrict: 'E',
    replace: true,
    link: function (scope, ele, attrs) {
        var testTemplate1 = '<h1 ng-repeat="x in arr">Test{{x}}</h1>';
        var testTemplate2 = '<h1>Test2</h1>';
        var testTemplate3 = '<h1>Test3</h1>';
        var template = '';   
        scope.arr  = eval(attrs.con);
        switch(attrs.content){
            case 'test1':
                template = testTemplate1;
                break;
            case 'test2':
                template = testTemplate2;
                break;
            case 'test3':
                template = testTemplate3;
                break;
        }

        ele.html(template);
        $compile(ele.contents())(scope);  

    }
  };
});



</script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-controller="fCtrl">
  <p>Result:</p>
  <datan-type content="test1" con="{{xx}}"></datan-type>
  <div id="test"></div>
  <button ng-click="add()">Add Form Elem Eg - Error Area</button>
</body>
</html>

【问题讨论】:

    标签: javascript angularjs dynamic angularjs-directive compilation


    【解决方案1】:

    Gary,这让我很生气,所以我早上的目标是找出愚蠢的语法:

    Working Plnkr - Clicky

    将您的控制器代码更改为:

    var elementToAdd = angular.element('<datan-type content="test1" con="{{xx}}"></datan-type>');
    $compile(elementToAdd)($scope);
    document.getElementById('test').appendChild(elementToAdd[0]);
    

    【讨论】:

    • 为什么会有不同?那是因为双向绑定在这里不起作用吗?
    • 我很确定 angular.element 中的 html 包装会导致编译以不同方式处理它。我对内部结构的了解还不够,无法告诉您到底是什么。如果您在网上查找示例,您通常会看到这样包装的 html,所以我只是假设这是标准的。
    • 我能否在同一代码中的控制器中使用this (controllerAs) 语法并让指令适用于 ng-repeat?
    • @Gary 当然,假设您使用了所有正确的符号。大多数人使用var vm = this,然后在 html 中分配东西给它vm.ID = 1,然后ng-model="vm.ID"。这允许您在任何地方使用点表示法,这是最佳实践。
    • 好酷。让我尝试。当我使用与 ng-repeat 相同的代码时,你的代码会中断
    猜你喜欢
    • 1970-01-01
    • 2016-05-19
    • 2015-10-25
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 2018-01-02
    • 1970-01-01
    相关资源
    最近更新 更多