AngularJS - How do I insert compiled HTML into my directive template?

I'm sure I am doing it wrong, so any help would be appreciated ...

Given the following plunker: http://plnkr.co/edit/hCjTdt8XmlVPKGgzvgFu?p=preview

I am trying to compile Html and paste it at a specific location in my template. However, I am getting the error:

Can't interpolate: My Value: {{innerHtml}}
TypeError: Converting circular structure to JSON

      

I'm sure this is because I am trying to insert the entire element as Html, but I am not sure how to accomplish what I am trying to do.

Plunger Code:

<!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>

      

+3


source to share


1 answer


I think you might be confused trying to access innerHtml in your scope? I think you need to access your element in order to insert the DOM. The element will be mostly in the template, but already compiled (link occurs after compilation). This way you can compile and add it to your element.

Try the following:



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

      

instead of a string scope.innerHtml

. Working at plnkr: http://plnkr.co/edit/z3k6BPVNcNxi6d4XBfXX?p=preview

+4


source







All Articles