Append html content to an iframe in Angular JS

后端 未结 2 1496
猫巷女王i
猫巷女王i 2020-12-19 10:22

I am trying to create a preview of a full fledged html document, meaning this html content is itself a complete html document with ,

相关标签:
2条回答
  • 2020-12-19 11:09

    The updated solution based on Chris's solution for people having issues with Firefox browser:

    var app = angular.module('App',[]);
    
    app.controller("Cont", function($scope){
      $scope.content = "Hi there!";
    });
    
    app.directive("preview", function () {
      function link(scope, element) {
        var iframe = document.createElement('iframe');
        var element0 = element[0];
        element0.appendChild(iframe);
    
        scope.$watch('content', function () {
          iframe.contentWindow.document.open('text/htmlreplace');
          iframe.contentWindow.document.write(scope.content);
          iframe.contentWindow.document.close();
        });
      }
    
      return {
        link: link,
        restrict: 'E',
        scope: {
          content: '='
        }
      };
    });
    
    0 讨论(0)
  • 2020-12-19 11:21

    I had to do something similar to what you're doing. I needed to make an editor for some HTML templates. The templates didn't preview well due to the CSS in the existing site, so I thought to display the template in an iframe.

    I was able to make an angular directive with a watch in it which would update: iframe.contentDocument.body.innerHTML and got me my desired effect. I believe you would be able to intercept the content here and make any replacements for placeholders inside your template as well.

    The preview directive below should help you on your way, if you still need it after all this time.

    var app = angular.module('App',[]);
    
    app.controller("Cont", function($scope){
      $scope.content = "Hi there!";
    });
    
    app.directive("preview", function () {
      function link(scope, element) {
        var iframe = document.createElement('iframe');
        var element0 = element[0];
        element0.appendChild(iframe);
        var body = iframe.contentDocument.body;
    
        scope.$watch('content', function () {
          body.innerHTML = scope.content;
        });
      }
    
      return {
        link: link,
        restrict: 'E',
        scope: {
          content: '='
        }
      };
    });
    input, iframe {
      border: solid 1px black;
      width: 100px;
    }
    preview iframe {
      height: 50px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="App" ng-controller="Cont">
      <input ng-model="content" type="text" /><br />
      <preview content="content"></preview>
    </div>

    0 讨论(0)
提交回复
热议问题