0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.