1

I am using a gist directive which seems to fail when I call compile on a controller's ajax response.

Here the the gist directive:

angular.module('gist', []);

angular.module('gist')
  .directive('gist', function () {
    return {
      restrict: 'E',
      replace: true,
      template: '<div></div>',
      link: function(scope, elm, attrs) {
        var gistId = attrs.id;

        var iframe = document.createElement('iframe');
        iframe.setAttribute('width', '100%');
        iframe.setAttribute('frameborder', '0');
        iframe.id = "gist-" + gistId;
        elm[0].appendChild(iframe);

        var iframeHtml = '<html><head><base target="_parent"><style>table{font-size:12px;}</style></head><body onload="parent.document.getElementById(\'' + iframe.id + '\').style.height=document.body.scrollHeight + \'px\'"><scr' + 'ipt type="text/javascript" src="https://gist.github.com/' + gistId + '.js"></sc'+'ript></body></html>';

        var doc = iframe.document;
        if (iframe.contentDocument) doc = iframe.contentDocument;
        else if (iframe.contentWindow) doc = iframe.contentWindow.document;

        doc.open();
        doc.writeln(iframeHtml);
        doc.close();
      }
    };
  });

And here is my controller:

angular.module('spa2App').controller('BlogEntryCtrl', ['$scope', '$routeParams', '$compile', 'BlogEntry', function($scope, $routeParams, $compile, BlogEntry) {
    $scope.Blog = BlogEntry.get({EntryID: $routeParams.EntryID}, function ($resource) {
        var dateTs = parseInt($resource.PubDate.match(/[0-9-]+/)[0]);
        $resource.PubDate = new Date(dateTs);
        $resource.Content = $compile($resource.Content)($scope);
    });
}]);

My view:

<div ng-bind-html="Blog.Content"></div>

When it tried to compile the html content from the ajax response I get an error from doc.open, because the iframe is not available. I've read that this is because the iframe is to be injected in the body, but if I do that then it goes into a compiling loop.

Joseph Montanez
  • 1,598
  • 1
  • 17
  • 31
  • I found a solution, creating a compile directive: http://stackoverflow.com/questions/17417607/angular-ng-bind-html-unsafe-and-directive-within-it – Joseph Montanez Feb 19 '14 at 02:11

0 Answers0