2016-01-21 52 views
1

UPDATE:解決方案如下添加答案創建一個從用戶inputed CSS和HTML預覽使用angularJS

林建設使用angularJS和王牌編輯一個片段馬槽裏。我有兩個CSS和HTML選項卡,我想根據用戶的輸入製作預覽選項卡,類似於http://bootsnipp.com/的工作方式。 我有一個預覽通過注入CSS代碼到一個樣式標記工作:

<div> 
    <style> 
     {{snippetsCtrl.snippet.css}} 
    </style> 
    <div ng-bind-html="snippetsCtrl.snippet.html"> 

    </div> 
</div> 

但我知道這是一個壞主意,如果用戶添加

它會影響應用程序的其他部分,例如
body { display: none; } 

屏幕變空白。

我試過使用iframe,但我不知道如何使iframe工作與角度。

因此,有關如何獲取$ scope中的代碼並將其應用於iframe的建議?

回答

0

好了,我管理,如果有人有興趣推測這一個與這些以前的問題的組合:

Is it possible to update angularjs expressions inside of an iframe?

Access AngularJS service from a service inside a different frame

Angularjs: call other scope which in iframe

我所做的是創建iframe作爲單獨的Angular應用程序。要發送的範圍的iframe應用程序,我用下面的代碼中我主要的應用程序控制器:

snippetsCtrl.updateIframe = function() { 
    document.getElementById('iframe').contentWindow.updatehtml(snippetsCtrl.snippet.html); 

    document.getElementById('iframe').contentWindow.updatecss(snippetsCtrl.snippet.css); 

}; 

然後在iframe app.js文件我用下面的代碼檢索到的數據添加到這個範圍應用程序。

var app = angular.module('iframeApp', ['ngSanitize']); 

app.controller('iframeCtrl', function ($scope) { 

$scope.html = "<h1>Add Code to see preview here</h1>"; 
$scope.css = ''; 

window.updatehtml = function (snippet) { 
    $scope.$applyAsync(function() { 
     $scope.html = snippet; 
    }); 
}; 
window.updatecss = function (snippet) { 
    $scope.$applyAsync(function() { 
     $scope.css = snippet; 
    }); 
}; 

}) 

這基本上是我如何得到它的工作,它有點混亂,但現在我覺得就可以了。

我遇到的一個問題是使用$ scope。$ apply,沒有任何工作,直到我更新到$ applyAsync,不知道爲什麼。

1

您將無法使用Angular修改iframe —的內容,這是由於Same-Origin Policy造成的。

我能想到的唯一方法就是創建第二個頁面,該頁面可以動態更新(不知道這對於Angular來說有多可能,它確實可以用ASP實現)。從頁面上的數據創建元素,填充第二頁的細節。然後用角到iframe的src更新到新頁面:

How to set an iframe src attribute from a variable in AngularJS

編輯:有一個問題Here其詢問使用的角度來創造一個全新的頁面。答案是「按照其他方式做你想做的事情」,但是看起來問題本身包含了一種用Angular創建單獨頁面的方法。