从不同框架内的服务访问AngularJS服务

时间:2015-02-04 10:09:13

标签: javascript angularjs iframe

在AngularJS应用程序(主要)中,我有一个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;
}

这可以实现吗?

我已阅读以下内容,但无法将其转变为解决方案,但是:

2 个答案:

答案 0 :(得分:7)

我设法做了一些有用的事情,对你有用。它并不完美但是一个好的开始。这是代码:

父页:

<div ng-controller="ParentController">
    <h1>Hello, parent page!</h1>

    <p><strong>Parent model:</strong></p>
    <p>
        <input type="text"
           ng-model="data.foo"
           placeholder="Enter the thing you want to share"/>
    </p>

    <p><strong>Parent result:</strong></p>
    <p>{{ data.foo }}</p>

    <iframe src="child-page.html" frameborder="0"></iframe>
</div>

子页面:

<div ng-controller="ChildController">
    <h1>Hello, child page!</h1>

    <p><strong>Child result:</strong></p>
    <p>{{ data.foo }}</p>
</div>

<强> app.js

var app = ng.module('myApp', []);

app.factory('DataService', ['$rootScope', '$window', function ($rootScope, $window) {
    var // Variables
        dataScope,

        // Functions
        getScope;

    dataScope = $rootScope.$new(true);

    getScope = function () {
        return dataScope;
    };

    $window.DataService = {
        getScope: getScope
    };

    return {
        getScope: getScope
    };
}]);

app.controller('ParentController', ['$scope', 'DataService', function ($scope, DataService) {
    $scope.data = DataService.getScope();
}]);

app.controller('ChildController', ['$scope', '$window', '$interval', function (
    $scope,
    $window,
    $interval
) {
    $scope.data = $window.parent.DataService.getScope();

    // makes a $scope.$apply() every 500ms. Without it, data doesn't change
    $interval(ng.noop, 500);
}]);

所有这些代码都会导致:

Working code

子控制器中的重要部分是$scope.data = $window.parent.DataService.getScope();。这就是它获取共享$ scope的地方。

当然,所有这一切只有在父母和父母的情况下才有效。 iframe属于同一个域。否则,它变成了另一个复杂的故事...

希望这会对你有所帮助。

答案 1 :(得分:6)

好的,所以这是我的解决方案,我希望这是你的想法。

在父应用程序的控制器中:

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/(结果)