编辑: 我调查了菲尔的评论了一下,并修正了(改写了)我的例子。最底层的掠夺者反映了这些变化。以下是更新后的代码:
app.controller('MainCtrl', function($scope, getStore) {
getStore.get().then(function(data) {
$scope.data = data
})
});
app.controller('ChildCtrl', function($scope, $timeout, getStore) {
$timeout(function() {
getStore.get().then(function(data) {
$scope.test = data
})
},3000)
});
app.factory('getStore', function($http, $q) {
var self = this;
var data;
return {
get: function() {
if (data) {
console.log(data);
console.log('already got data')
return $q.when(data)
} else {
data = $http.get('test.json')
.then(function(response) {
console.log('fetched data')
return response.data;
})
return data
}
}
}
})
这里是一个解决方案 - 分开你的$ http.get到工厂和存储的价值在那里。工厂是单身人士,所以两个控制器都可以访问和检查数据。
JS:
app.controller('MainCtrl', function($scope, getStore) {
$scope.data = getStore.get()
});
app.controller('ChildCtrl', function($scope, $timeout, getStore) {
$timeout(function() {
$scope.data = getStore.get()
var check = getStore.checkData();
console.log('Data in store: ' + angular.toJson(check));
},1000)
$scope.getData = function() {
console.log(getStore.get());
}
});
app.factory('getStore', function($http) {
var self = this;
return {
data: undefined,
get: function() {
if (self.data) {
console.log('already got data')
return self.data
} else {
$http.get('test.json')
.success(function(data) {
console.log('no data found');
self.data = data;
console.log(self.data);
return self.data;
})
}
}
}
})
它只是运行检查,以查看该值是否已经存储或没有,然后返回它,如果它是的,如果不是,它得到,商店,并将其返回。
Plunker
你能对$ scope.items做一些验证吗? if(!$ scope.items){Product.getItem()...} – tpie
否,因为当通过http请求加载页面时,$ scope.items始终未定义。 – FlyingCat
如果**子控制器**确实是**父控制器**的孩子,那么它将继承父范围,从而继承'$ scope.items'。 – Phil