【问题标题】:display HTML $scope variable in iframe as content在 iframe 中将 HTML $scope 变量显示为内容
【发布时间】:2017-01-30 00:20:39
【问题描述】:

我想在 iframe 中显示 Angular 1.2 中的一些 HTML,但我没有 URL,而是将内容放在变量中。如何显示?

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

【问题讨论】:

    标签: javascript jquery angularjs iframe


    【解决方案1】:

    我为此做了一个指令......它非常丑陋,但如果你愿意,你可以了解要点并清理它。

    .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);
    
        }
      }
    })
    

    你会像这样使用它

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

    还可能注意到这并没有对其写入文档的信息进行任何验证,因此如果这是用户可以输入数据的地方,那么网站上将显示您可能希望使用某些组件进行研究( s) 的 $sce 也在这里。

    【讨论】:

      猜你喜欢
      • 2014-08-04
      • 2017-11-12
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 1970-01-01
      • 2019-09-29
      相关资源
      最近更新 更多