我正在使用 AngularJS 编写我的第一个应用程序,但我被困在某个需要跨不同控制器共享数据的地方。
我有这样的事情:
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>
根据这个非常好的答案data
,如果它没有在子范围中设置并且在父范围中设置,我应该能够读取和设置属性。
为什么这不起作用?
[编辑]
现在想通了,这是解决方案。在将其添加到 DOM 之前,我必须将$compile注入我的并用它编译代码。ctrl2
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));
});
}