Currently tackling my first AngularJS app and facing a challenge in terms of sharing data across different controllers.
This is what I have so far:
function ctrl1 ($scope) {
$scope.data = new Object();
}
function ctrl2 ($scope, $http) {
$http.get('my_page').success(function(html) {
// Setting values to the parent's data object
$scope.data['my_key'] = 'My value';
// The loaded html includes ng-controller='ctrl3' somewhere
$('#mydiv').html(html);
// Therefore, it needs to be bootstrapped
angular.bootstrap($('#mydiv'), ['my_module']);
});
}
// Not a child of ctrl2, but a child of ctrl1
function ctrl3 ($scope) {
$scope.my_key = $scope.data.my_key; // Error: Cannot read property 'my_key' of undefined
// When trying to display my_key in an ng-repeat, nothing shows up.
// However, manually setting my_key here results in correct display.
// This indicates that controller and ng-repeat are parsed correctly post-bootstrap
}
The HTML structure looks like this:
<div ng-controller="ctrl1">
<div ng-controller="ctrl2">
<!-- some content -->
</div>
<!-- additional code -->
<div id="myDiv">
<!-- currently empty, will populate with AJAX-loaded html containing ng-controller="ctrl3" (alongside my ng-repeat) -->
</div>
</div>
As per this informative response, accessing and updating properties of data
should work if not set in the child scope but in the parent scope.
What could be causing this issue?
[UPDATE]
Mystery solved, here's the fix. It was essential to include $compile in my ctrl2
and compile the code before appending it to the DOM.
function ctrl2 ($scope, $http, $compile) {
$http.get('my_page').success(function(html) {
// Setting values to the parent's data object
$scope.data['my_key'] = 'My value';
// The loaded html includes ng-controller='ctrl3' somewhere
// ** Must compile before adding to the DOM
$('#mydiv').html($compile(html)($scope));
});
}