2

是否可以从我的控制器向我的 $resource $cacheFactory 添加值并在多个控制器之间保持这些数据同步?基本上我想要完成的是:

1)从 API 中提取 JSON 资源

2)操作 JSON,就好像它不再是 $resource 一样,只是我可以在控制器之间使用的普通 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
}
4

1 回答 1

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);
    

参考

于 2016-02-03T22:59:58.617 回答