2015-02-04 2 views
10

AngularJS 애플리케이션 (주)에는 내 제어하에 또 다른 AngularJS 애플리케이션 (iframe)이있는 iframe이 있습니다. 주 응용 프로그램과 iframe 응용 프로그램에서 두 가지 서비스간에 데이터를 공유하고 싶습니다. 그들은 모두 동일한 객체를 읽고 쓸 필요가 있습니다.다른 프레임 내의 서비스에서 AngularJS 서비스에 액세스

var self = this; 
var parentScope = $window.parent.angular.element($window.frameElement).scope(); 
parentScope.$watch('serviceA.sharedData', function (newValue, oldValue) { 
    self.sharedData = newValue; 
} 

이 달성 할 수있는 방법 :

// 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를 참조하는 관리?

나는 다음을 읽고, 아직, 솔루션으로 바꿀 수 없습니다 :

+0

당신이 언급 한 두 번째 질문에 대한 대답은 당신이 theIFrameElement'와 iframe이의 각 개체에 액세스 할 수 있다고 말한다 .contentWindow.angular'. 그게 너에게 효과가 있니? – user1950929

+0

예, 이와 같이 'angular'객체에 액세스 할 수 있습니다. 그런데 어떻게 등록 된 서비스에 액세스 할 수 있습니까? – hielsnoppe

+0

서비스를 컨트롤러의 범위에 추가하면 외부 (즉, 상위 프레임)에서 액세스 할 수 있습니다. – user1950929

답변

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

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에서 작동하지 않습니다 (공유 서비스에 대한 JS 파일 만 parent.html으로 포함 할 필요가) 그래서 나는 내 더 다양한 예제를 넣어 GitHub의 페이지 :

https://github.com/sammax/angulariframe (코드)

http://sammax.github.io/angulariframe/main/ (결과)

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> 

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); 
}]); 

모두 app.js 여기에 코드입니다 이 코드의이 리드 :

Working code

중요한 부분은 자식 컨트롤러 $scope.data = $window.parent.DataService.getScope();입니다. 그것이 공유 $ 범위를 가져 오는 곳입니다.

물론이 모든 것은 부모 & iframe이 동일한 도메인 아래에있는 경우에만 작동합니다. 다른 모든 복잡한 이야기가됩니다 ...

희망이 도움이 될 것입니다.

+0

jsfiddle please를 만드십시오 .... –

관련 문제