【发布时间】:2015-01-14 08:57:16
【问题描述】:
我有两个不同的 Angular 应用程序。我必须在“app_1”中使用 iframe 打开“app_2”的视图。 我还需要将一些数据从“app_1”发布到“app_2”。 如何在 angularJS 中实现这一点?
提前致谢。 #SOS
【问题讨论】:
-
为什么要在两个不同的 iframe 中渲染这两个应用程序?这样做你会达到什么目的?
我有两个不同的 Angular 应用程序。我必须在“app_1”中使用 iframe 打开“app_2”的视图。 我还需要将一些数据从“app_1”发布到“app_2”。 如何在 angularJS 中实现这一点?
提前致谢。 #SOS
【问题讨论】:
我会考虑使用postMessage...
在 Angular 术语中,这意味着一个应用程序将发送消息,而另一个应用程序将监听消息。
因此,在 iframe 中的应用程序上,您可以创建一个执行以下操作的工厂:
/**
* App that sits within iframe:
*
* Inject this factory into your controller and call
* iFrame.messageParentIframe({hello: 'world'}) to send messages
* to the parent iFrame
*/
angular
.module('app')
.factory('iFrameMessenger', function($window) {
return {
messageParentIframe: function(message) {
$window.parent.postMessage(message, '*');
}
};
});
在父 iFrame 上,您的代码应如下所示:
/**
* App that is on parent iframe:
*
* Just using a controller for the sake of simplicity,
* but you could also use a Factory that only receives
* messages from iFrames and handle them according to each
* action, etc. You can get creative here on how you want
* to handle it.
*/
angular
.module('app')
.controller('AppCtrl', function($window) {
$window.addEventListener('message', function() {
// handle messages received from iframe
});
});
【讨论】: