无法将动态添加的指令编译到页面中

时间:2016-07-29 13:47:04

标签: javascript angularjs dynamic angularjs-directive compilation

我正在尝试将一个动态添加的元素指令添加到页面中,但它无法正常工作并在添加的页面中进行编译。这是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>

1 个答案:

答案 0 :(得分:3)

加里,这让我很伤心,所以我把它作为早上的目标,找出了愚蠢的语法:

Working Plnkr - Clicky

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

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

enter image description here