Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm pretty sure I'm doing this the wrong way, so any help would be appreciated...

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

I'm trying to compile some Html and insert it in a specific location in my template. However, I'm getting an error:

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

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

Plunker 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>
like image 242
Scottie Avatar asked May 19 '26 19:05

Scottie


1 Answers

I think you may be confused by trying to access innerHtml on your scope? I think you need to be accessing your element to insert DOM. The element will be basically whatever's in your template, but already compiled (link happens after compile). So you can compile and add it to your element.

Try this:

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

instead of scope.innerHtml line. Working in plnkr: http://plnkr.co/edit/z3k6BPVNcNxi6d4XBfXX?p=preview

like image 139
Jonathan Rowny Avatar answered May 22 '26 11:05

Jonathan Rowny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!