不应该$ cacheFactory#get()返回缓存对象的副本而不是引用?

时间:2015-12-13 12:18:47

标签: angularjs cachefactory

我在使用$cacheFactory时遇到了一个我没想到的情况,不应该在缓存中存储的对象不受$cacheFactory之外的更改的影响,意味着使用$ cacheFactory.get从缓存返回的对象()不应该将更改反映回当前的缓存对象。

我有一个示范:http://jsfiddle.net/vladimir_ze/s9twdbup/

1 个答案:

答案 0 :(得分:0)

// get model from cache and modify it
$scope.modelFromCache = cache.get('model');
$scope.modelFromCache.author.name = 'Bob';

// Telling you're right and instead of copy you get a reference
console.log($scope.modelFromCache === cache.get('model')); // true

$scope.anotherModelFromCache = angular.copy(cache.get('model')); 

// Solution if you just want a copy of cache property data
console.log($scope.anotherModelFromCache === cache.get('model')); // false

我认为你是对的,应该明确这种行为,因为

  

检索存储在Cache对象中的命名数据。

有点误导......

参考。 https://docs.angularjs.org/api/ng/type/ $ cacheFactory.Cache

好赶上顺便说一句:)