In an AngularJS application (main) I have an iframe
inside which there is another AngularJS application (iframe) also under my control. I would like to share data between two services, one in the main application and one in the iframe application. They both need to read and write to the same object.
// 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
}
// ...
When inside a controller in iframe application I managed to reference serviceA.sharedData
like this:
var self = this;
var parentScope = $window.parent.angular.element($window.frameElement).scope();
parentScope.$watch('serviceA.sharedData', function (newValue, oldValue) {
self.sharedData = newValue;
}
Can this be achieved and how?
I have read the following, but could not turn it into a solution, yet:
I managed to do something that works, and could be useful for you. It's not perfect but is a good start. Here is the code:
Parent page:
Child page:
app.js
All of this code leads to this:
The important part is
$scope.data = $window.parent.DataService.getScope();
in the child controller. That's where it fetches the shared $scope.Of course, all this works only if the parent & the iframe are under the same domain. Else, it becomes a whole other complicated story...
Hope this will help you.
Ok, so here is my solution, I hope this is what you had in mind.
in the controller of the parent application:
in the controller of the iframe application:
});
sharedData.js (the js file for the shared service, needs only be included by
parent.html
)The stuff with the iframes doesn't work on jsfiddle (cross-origin maybe) so I put my more extensive example on a github page:
https://github.com/sammax/angulariframe (code)
http://sammax.github.io/angulariframe/main/ (result)