我正在尝试解决我使用AngularJS构建页面的问题以及需要同样具有角度的域iframe的功能。
我想要实现的是使用$ rootScope广播来自iframe的消息。$ broadcast使其达到父框架。
我在考虑做这样的事情:
app.config(['$provide', function ($provide) {
$provide.decorator('$rootScope', ['$delegate', function ($delegate) {
var native = $delegate.$broadcast;
$delegate.$broadcast = function (name, args) {
if (window.frameElement) {
console.log("Broadcast inside a frame");
// Here I would do window.postMessage
} else {
console.log("Broadcast outside a frame");
}
return native;
}
return $delegate;
}]);
但这会因角度误差而爆炸。有关修复此错误的任何建议吗?有没有更好的方法来做我正在寻找的东西?
答案 0 :(得分:3)
我认为这就是你所追求的。你对这个'这个'的价值问题是正确的,将$ broadcast副本存储到$ delegate似乎可以解决问题
http://plnkr.co/edit/KW3whFtuu9C9Tvjo4kdS?p=preview
app.config(['$provide', function ($provide) {
$provide.decorator('$rootScope', ['$delegate', '$window', function ($delegate, $window) {
$delegate.native = angular.copy($delegate.$broadcast);
$delegate.$broadcast = function (name, args) {
if ($window.parent) {
$window.parent.postMessage(args, '*');
console.log("Broadcast inside a frame");
// Here I would do window.postMessage
} else {
console.log("Broadcast outside a frame");
}
$delegate.native(name, args);
return $delegate.native;
}
return $delegate;
}]);
}]);
这是另一种做同样事情的方法。 (我把它留在这里,因为这是我的原始答案,然后才让装饰器版本工作。)
http://plnkr.co/edit/s5qNtva1l0SJVV2y0Onk?p=preview
app.run(function($rootScope, $window){
$rootScope.oldBroadcast = angular.copy($rootScope.$broadcast);
$rootScope.$broadcast = function (name, args) {
if ($window.parent) {
$window.parent.postMessage(args, '*');
console.log("Broadcast inside a frame", name, args);
// Here I would do window.postMessage
} else {
console.log("Broadcast outside a frame");
}
$rootScope.oldBroadcast(name, args);
return $rootScope.oldBroadcast;
}
});