gpt4 book ai didi

javascript - 从子窗口访问父窗口 Angular 范围

转载 作者:可可西里 更新时间:2023-11-01 02:54:42 25 4
gpt4 key购买 nike

我正在尝试从子弹出窗口更新父窗口上的范围值。但是每当我尝试访问父窗口范围时,它都会返回未定义。因为它涉及两个窗口,所以我无法为此创建 fiddle 。代码示例粘贴在下面。

主页 (main.html)

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.name = 'Superhero';
}
</script>
</head>
<body ng-app="myApp">
<div id="ctrl" ng-controller="MyCtrl">
Hello, {{name}}!
<input type="button" value="Open popup!!" onclick="window.open('child.html');"/>
</div>
</body>
</html>

子窗口(child.html)

<!doctype html>
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
function change(){
var e = window.opener.document.getElementById('ctrl');
var ae = angular.element(e);
var s = ae.scope();
s.name="New Superhero";
s.$apply();
}
</script>
</head>
<body>
<input type="button" value="Update parent scope!" onclick="change();"/>
</body>
</html>

在这里,每当我尝试从 Angular 元素访问范围时,如上所示的更改方法,它返回未定义的 [ae.scope()]。但是当相同的代码移动到父窗口中的函数时 [唯一不同的是如何'ctrl' 元素正在被访问],它工作正常,我能够更新范围变量。谁能指出这里到底出了什么问题?谢谢

最佳答案

使用 opener 中的 angular 引用:

function change() {
var s = window.opener.angular.element('#ctrl').scope();
s.name="New Superhero";
s.$apply();
}

关于javascript - 从子窗口访问父窗口 Angular 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17007939/

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