I'm writing my first app using AngularJS, and I'm stuck at some point where I need to share data across different controllers.
I have something like this :
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
}
Here is the 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>
According to this very nice answer, I should be able to read and set properties of data
if it's not set in the child scope and is set in the parent scope.
Why isn't this working?
[EDIT]
Figured it out now, here's the solution. I had to inject $compile into my ctrl2
and compile the code with it before adding it to the 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));
});
}