gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:37:43 26 4
gpt4 key购买 nike

在 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 应用程序的 Controller 内部时,我设法像这样引用 serviceA.sharedData:

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

这可以实现吗?如何实现?

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

最佳答案

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

父页面:

<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

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

当然,所有这些只有在父级和 iframe 在同一个域下时才有效。否则,它会变成另一个复杂的故事......

希望对您有所帮助。

关于javascript - 从不同框架内的服务访问 AngularJS 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28318633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com