在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页面上:
https://github.com/sammax/angulariframe(代码)
http://sammax.github.io/angulariframe/main/(结果)