gpt4 book ai didi

javascript - 需要帮助理解 $scope 继承(并将新生成的内容添加到 Angular)

转载 作者:行者123 更新时间:2023-11-30 12:58:49 24 4
gpt4 key购买 nike

我正在使用 AngularJS 编写我的第一个应用程序,但我遇到了需要在不同 Controller 之间共享数据的问题。

我有这样的东西:

function ctrl1 ($scope) {
$scope.data = new Object();
}

function ctrl2 ($scope, $http) {
$http.get('my_page').success(function(html) {
// I set some values to the parent's data object
$scope.data['my_key'] = 'My value';
// The html loaded here contains a ng-controller='ctrl3' somewhere
$('#mydiv').html(html);
// So I bootstrap it
angular.bootstrap($('#mydiv'), ['my_module']);
});
}

// Is not a child of ctrl2, but is a child of ctrl1
function ctrl3 ($scope) {
$scope.my_key = $scope.data.my_key; // Cannot read property 'my_key' of undefined
// And in an ng-repeat where I want to display my_key, nothing is shown.
// However, if I manually set my_key here, everything is displayed correctly.
// So the controller and ng-repeat are correctly parsed after bootstrapping
}

这是 HTML:

<div ng-controller="ctrl1">
<div ng-controller="ctrl2">
<!-- some content -->
</div>
<!-- some more code -->
<div id="myDiv">
<!-- currently empty, will be added html with AJAX, ang ng-controller="ctrl3" is in this (as well as my ng-repeat) -->
</div>
</div>

根据 this very nice answer ,我应该能够读取和设置 data 的属性,如果它不是在子范围中设置而是在父范围中设置的话。

为什么这不起作用?

[编辑]

现在想通了,这是解决方案。我不得不注入(inject) $compile进入我的 ctrl2 并在将代码添加到 DOM 之前用它编译代码。

function ctrl2 ($scope, $http, $compile) {
$http.get('my_page').success(function(html) {
// I set some values to the parent's data object
$scope.data['my_key'] = 'My value';
// The html loaded here contains a ng-controller='ctrl3' somewhere
// ** Have to compile it before appending to the DOM
$('#mydiv').html($compile(html)($scope));
});
}

最佳答案

您在这里看到的问题不是范围继承,问题是您对 angular.bootstrap 的调用:

angular.bootstrap($('#myDiv'), ['my_module']);

这告诉 Angular 应用程序的根 DOM 元素是 #myDiv,所以你的 ng-controller="ctrl1"ng-controller ="ctrl2" 不被视为此应用程序的一部分。因此您得不到预期的结果。

修复:

<div id="myContainer" ng-controller="ctrl1">
<div ng-controller="ctrl2">
<!-- some content -->
</div>
<!-- some more code -->
<div id="myDiv">
<!-- currently empty, will be added html with AJAX, ang ng-controller="ctrl3" is in this (as well as my ng-repeat) -->
</div>
</div>

在 JS 中:

angular.bootstrap($('#myContainer'), ['my_module']);

关于javascript - 需要帮助理解 $scope 继承(并将新生成的内容添加到 Angular),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18084153/

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