Reputation: 3927
I have this plunkr. I define two controllers: mainController
and itemsController
. I want to access to the scope variable items
from a view, but I can't.
To reproduce, you need to click first in the button Populate Items
, (the array item is populated from a service
) and you see in the console
the values. Then click in the button Say Hello !
and then you will see that items is empty; but, the variable tab
is being accessed.
I think that I'm not applying in the correct way the definitions of the controllers.
Upvotes: 1
Views: 164
Reputation: 123861
There is updated and working plunker
What we need, is the data sharing:
so instead of this
app.controller("itemsController",
function($rootScope, $scope, $state, $stateParams, Data) {
$scope.items = []; // local reference, not shared
$scope.getFromJson = function() {
Data.get().then(function handleResolve(resp) {
$scope.items = resp;
console.log($scope.items);
});
};
})
we will fill the shared reference $scope.Model.items = resp;
app.controller("itemsController",
function($rootScope, $scope, $state, $stateParams, Data) {
$scope.getFromJson = function() {
Data.get().then(function handleResolve(resp) {
$scope.Model.items = resp;
console.log($scope.Model.items);
});
};
})
which will be hooked on the super root home. So, instead of this:
$stateProvider
.state("home", {
abtract: true,
url: "/home",
resolve: {
$title: function() {
return 'Tab1';
}
},
views: {
"viewA": {
templateUrl: "home.html"
}
}
});
we will have that:
.state("home", {
abtract: true,
url: "/home",
resolve: {
$title: function() {
return 'Tab1';
}
},
views: {
"viewA": {
templateUrl: "home.html",
// HERE we do the magic
// this is a super parent view
// at which $scope we will have shared reference Model
controller: function($scope){
$scope.Model = {}
}
}
}
});
check it in action here
Upvotes: 1