在AngularJS应用程序(main)中,我有一个iframe,其中还有另一个AngularJS应用程序(iframe)也在我的控制之下.我想在两个服务之间共享数据,一个在主应用程序中,一个在iframe应用程序中.他们都需要读写同一个对象.
// main // ... routes ... views: { main: { controller: function ($scope,serviceA) { $scope.serviceA = serviceA; },templateUrl: 'iframe.html' } // ... function ServiceA () { this.sharedData; // exposed to controllers in main app } // ... // iframe // ... function ServiceB () { this.sharedData; // exposed to controllers in iframe app } // ...
当在iframe应用程序中的控制器内部时,我设法引用了serviceA.sharedData,如下所示:
var self = this; var parentScope = $window.parent.angular.element($window.frameElement).scope(); parentScope.$watch('serviceA.sharedData',function (newValue,oldValue) { self.sharedData = newValue; }
这可以实现吗?
> Bind angular cross iframes,possible?
> Angularjs: call other scope which in iframe
解决方法
好的,所以这里是我的解决方案,希望这是你想到的.
在父应用程序的控制器中:
mainApp = angular.module('mainApp',[]); mainApp.controller('mainCtrl',['$scope','sharedData',function($scope,sharedData){ $scope.sharedData = sharedData; //your controller logic goes here ... }]);
在iframe应用程序的控制器中:
iframeApp = angular.module('iframeApp',[]); iframeApp.controller('iFrameCtrl',function($scope){ //here we get the service instance from the parent application,if you //need it in other controllers in the iframe app as well,either get it //there the same way or pass it along via $scope or $rootScope var sharedData = window.parent.angular.element(window.frameElement).scope().sharedData; //now we can use sharedData the same way as in the parent application controller
});
sharedData.js(共享服务的js文件,只需要由parent.html包含)
mainApp.factory('sharedData',function(){ var list = []; var mainScope; var iframeScope; //this function needs to be called in all setter methods to update the data in both applications function update(){ if(!mainScope){ mainScope = angular.element(document.body).scope(); } //$apply() causes errors in the dev console,$applyAsync doesn't,I don't know why mainScope.$applyAsync(); if(!iframeScope){ //the update function might be called before angular is initialized in the iframe application if(document.getElementById('iframe').contentWindow.angular){ iframeScope = document.getElementById('iframe').contentWindow.angular.element(document.body).scope(); iframeScope.$applyAsync(); } } else { iframeScope.$applyAsync(); } } return { append: function(item) { list.push(item); //don't forget to add this at the end of all setter functions in the service update(); },getAll: function() { return list } } });
与iframe的东西不适用于jsfiddle(跨原产也许),所以我把更广泛的例子放在github页面上: