好的,如果有人感兴趣的话,我设法结合这些以前的问题来解决这个问题:
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 之前没有任何效果,不知道为什么。