【问题标题】:update $cacheFactory from controller从控制器更新 $cacheFactory
【发布时间】:2016-01-07 17:21:28
【问题描述】:

是否可以从我的控制器向我的 $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
}

【问题讨论】:

标签: angularjs angular-services cachefactory


【解决方案1】:

使用以下流程:

  • 创建恒定配方
  • 注入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-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 2015-04-30
    • 2015-11-19
    • 2015-11-30
    • 1970-01-01
    相关资源
    最近更新 更多