Pentium10
Pentium10

Reputation: 207893

display HTML $scope variable in iframe as content

I want to display some HTML in Angular 1.2 in an iframe, but I don't have an URL, instead I have the content in a variable. How to display it?

$scope.serverMessage = $sce.trustAsHtml(data);
$scope.switchMessage('serverError'); // this displays a modal with iframe in it

Upvotes: 0

Views: 242

Answers (1)

shaunhusain
shaunhusain

Reputation: 19748

I made a directive for this... it's pretty ugly but you can get the gist and clean it up if you'd like.

.directive('dynamicIFrame', function($document){
  return {
    restrict:'E',
    scope:{
      html:"="
    },
    link:function(scope, iElem, iAttr){
      // Create an IFrame and add it to the current element
      var iframe = $document[0].createElement("iframe");
      iframe.style.width="98%"
      iframe.style.height="500px"
      iElem.append(iframe);

      // Do some things to get a DOM Document out of the iframe
      var doc = iframe.document;
      if(iframe.contentDocument){
        doc = iframe.contentDocument;
      }
      else if(iframe.contentWindow){
        doc = iframe.contentWindow.document;
      }

      // watch whatever gets passed into here as HTML so the
      // iframe contents will just update if the HTML changes

      // uses lodash's debounce function to delay updates by 250ms
      scope.$watch('html', _.debounce(function(newVal,oldVal){
          console.log('html changed')
          if(!newVal)
            return;
          doc.open();
          doc.writeln(newVal);
          doc.close();
        }, 250),
        true);

    }
  }
})

You would use it like

<dynamic-i-frame html="someVarWithHTMLInIt"></dynamic-i-frame>

Also probably notice this isn't doing any validation on the info it's writing into the document so if this will be something where users can enter data in that will show up on the site you may want to look into using some component(s) of $sce in here as well.

Upvotes: 1

Related Questions