2016-09-21 40 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中的某些組件進行查看。