In this plunk我有一个包装Angular' $cacheFactory
的工厂。控制器使用工厂创建两个独立的缓存,但是我收到以下错误:cacheManager is not a function
。这段代码有什么问题?
HTML
<body ng-app="app" ng-controller="myCtl">
cache1 : {{cache1 | json}}
<br/>
cache2 : {{cache2 | json}}
</body>
使用Javascript:
var app = angular.module('app',[]);
app.controller('myCtl', function ($scope,cacheManager) {
var cache1 = new cacheManager();
var cache2 = new cacheManager();
cache1.create("cache1");
cache2.create("cache2");
cache1.add("key1", "value1");
cache2.add("key2", "value2");
})
.factory('cacheManager',function($cacheFactory){
var factory = {};
var cache = null;
factory.create = function(cacheId){
cache = $cacheFactory(cacheId);
return cache;
};
factory.add = function(key,value){
if (!cache)
return;
cache.put(key, value);
}
factory.get = function(key){
if (!cache)
return;
return cache.get(key);
}
return factory;
});
答案 0 :(得分:0)
这是执行该技巧的代码,工厂需要返回一个允许控制器执行新功能的函数。此外,需要使用prototype
关键字定义方法:
var app = angular.module('app',[]);
app.controller('myCtl', function ($scope,cacheManager) {
var cache1 = new cacheManager();
var cache2 = new cacheManager();
cache1.create("cache1");
cache2.create("cache2");
cache1.add("key1", "value1");
cache2.add("key2", "value2");
alert(cache1.get("key1"));
})
.factory('cacheManager',function($cacheFactory){
var factory = function() { };
factory.cache = null;
factory.prototype.create = function(cacheId){
cache = $cacheFactory(cacheId);
return cache;
};
factory.prototype.add = function(key,value){
if (!cache)
return;
cache.put(key, value);
}
factory.prototype.get = function(key){
if (!cache)
return;
return cache.get(key);
}
return factory;
});
答案 1 :(得分:0)
cacheManager是一个Object,它不是一个函数()
cacheManager.create("cache1");
cacheManager.create("cache2");
cacheManager.add("key1", "value1");
cacheManager.add("key2", "value2");
答案 2 :(得分:0)
我认为您不应该创建多个cacheManager实例,而应该创建多个缓存对象并将多个键/值添加到不同的缓存对象。
var cache1 = cacheManager.create("cache1");
var cache2 = cacheManager.create("cache2");
cache1.add(“key1”,“value1”); cache2.add(“key2”,“value2”);