2016-09-21 2 views
0

iframeにAngular 1.2でHTMLを表示したいのですが、URLがなく、代わりに変数にコンテンツがあります。それを表示するには?

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

答えて

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> 

のようにそれを使用しますこのサイトでも$ sceのいくつかのコンポーネントを使って調べたいサイトに表示されます。

関連する問題