AngularJS - 如何将编译的HTML插入到我的指令模板中?

Sco*_*tie 3 angularjs angularjs-directive

我很确定我这样做是错误的,所以任何帮助都会受到赞赏......

鉴于以下plunker:http://plnkr.co/edit/hCjTdt8XmlVPKGgzvgFu?p = preview

我正在尝试编译一些Html并将其插入我模板中的特定位置.但是,我收到一个错误:

Can't interpolate: My Value: {{innerHtml}}
TypeError: Converting circular structure to JSON
Run Code Online (Sandbox Code Playgroud)

我很确定这是因为我试图将整个元素作为Html插入,但我不知道如何完成我想要做的事情.

Plunker代码:

<!DOCTYPE html>
<html>

  <head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  </head>

  <body ng-app='myApp'>
    <div ng-controller='TestCtrl'>
      <test-directive></test-directive>
    </div>
    <script>
      var app = angular.module('myApp', []);

      app.controller("TestCtrl", ['$scope', function($scope) {
        $scope.myValue = "Hello, World!";
      }]);

      app.directive('testDirective', ['$compile', function($compile) {
        return {
          restrict: 'E',
          template: "<h1>Title</h1>My Value: {{innerHtml}}",
          link: function (scope, element, attr) {
            scope.innerHtml = $compile("<input type='text' ng-model='myValue' />")(scope);
          }
        }
      }]);
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Jon*_*wny 5

我想您可能会因为尝试访问范围内的innerHtml而感到困惑?我认为你需要访问你的元素来插入DOM.元素基本上是模板中的任何元素,但已编译(链接在编译后发生).因此,您可以编译并将其添加到元素中.

试试这个:

element.append($compile("<input type='text' ng-model='myValue' />")(scope));
Run Code Online (Sandbox Code Playgroud)

而不是scope.innerHtml线.在plnkr中工作:http://plnkr.co/edit/z3k6BPVNcNxi6d4XBfXX?p = preview