如何在2个角度应用程序之间使用iframe进行通信?

时间:2015-01-14 08:57:17

标签: angularjs iframe

我有两个不同的角度应用程序。我必须在“app_1”中使用iframe打开“app_2”视图。 我还需要将某些数据从“app_1”发布到“app_2”。 如何在angularJS中实现这一点?

提前致谢。 #SOS

1 个答案:

答案 0 :(得分:15)

我会考虑使用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
    });
  });