是否可以从我的控制器& amp;添加值到我的$ resource $ cacheFactory保持这些数据在多个控制器之间同步?基本上我想要完成的是:
1)从API中提取JSON资源
2)操纵JSON就好像它不再是$资源一样,只是一个普通的JSON对象,我可以在控制器之间使用。
是否有“角度方式”来执行此操作,或者我应该使用本地存储和放大器来缓存整个地点列表?从那里读写其他所有内容?
.factory('places', ['$resource','environment','$cacheFactory',
function($resource, environment, $cacheFactory) {
var cache = $cacheFactory('places');
return $resource(environment.apis.places, {}, {
query: {
isArray:true,
method: 'GET',
cache: cache
}
});
}
])
.controller('ItemCtrl', function($scope, places) {
places.query({}, function(result){
$scope.item = result[0]
})
$scope.makeFav = function(index){
//add a new key to cached places data
$scope.item.fav = true
}
}
.controller('ListCtrl', function($scope, places) {
places.query({}, function(result){
$scope.item = result //should get the updated cache changed by ItemCtrl
})
console.log($scope.item[0].fav) //should = true
}
答案 0 :(得分:0)
使用以下过程:
cacheFactory
cacheFactory
cacheFactory
在每个控制器中操纵cacheFactory
的实例
function sharedCache($cacheFactory)
{
var sharedCache = $cacheFactory.get('sharedCache') ? $cacheFactory.get('sharedCache') : $cacheFactory('sharedCache');
return sharedCache;
}
function bar(sharedCache, $scope)
{
sharedCache.put('config', $scope.config);
}
bar.$inject = ['sharedCache', '$scope'];
sharedCache.$inject = ['$cacheFactory'];
angular.module('foo',[]);
angular.module('foo').constant('sharedCache', sharedCache);
angular.module('foo').controller('bar', bar);
<强>参考强>