I have a list
object in the parent state of this controller. Every time I load the state that uses this controller, $scope.items
is emptied and the controller must load the data from the parent scope again.
ListCtrl
corresponds to the list
state. The parent state contains many lists.
.controller('ListCtrl', ['$scope','$state','$timeout',
function($scope, $state, $timeout) {
console.log($scope.items); // undefined
if(!$scope.items) { // always evaluates to true
$timeout(function() {
$scope.items = $scope.$parent.list.items;
}, 500);
} else {
console.log($scope.items); // never executes here
}
}])
It was my understanding that AngularJS by default caches some views. Does this mean the caching does not apply to the scope variables in the cached views? And most importantly, is there a way to cache this $scope.items
so that every time I return to this state, there isn't this timeout delay?
As a beginner of AngularJS, what I understand is that $scope.items is only defined within the current controller. If you want to load items in your html content, just define items under that controller used in that specified html tag.
I made up a toy example ,
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
$scope.username = 'World';
}]);
which is similar to that on AngularJS Scope documentation.
Parent Controller
.controller('parentController', ['$scope','$state','$timeout','$rootScope'
function($scope, $state, $timeout, $rootScope) {
$rootScope.items=['item 1','item 2'];
}])
Another Controller
.controller('ListCtrl', ['$scope','$state','$timeout','$rootScope'
function($scope, $state, $timeout,$rootScope) {
console.log($rootScope.items); // Should give the result
if(!$scope.items) { // always evaluates to true
$timeout(function() {
$scope.items = $scope.$parent.list.items;
}, 500);
} else {
console.log($scope.items); // never executes here
}
}])
Dont forget to add $rootScope on top.
The solution ended up being to check if the $rootScope.list.item had been loaded, instead of just the $scope.item.
if(!$rootScope.list) {
$timeout(function() {
$scope.items = $rootScope.list.items;
}, 1000);
} else {
$scope.items = $rootScope.list.items;
}