【发布时间】:2015-07-15 09:27:28
【问题描述】:
我不想将我的所有代码都放在一个巨大的控制器中,所以我正在尝试对其进行一些重构,但我遇到了这个错误
Argument 'protocolController' is not a function, got undefined
我有我的工厂
/*
FACTORY THAT HANDLES ALL REQUESTS.
*/
function asyncFactory() {
var factory = this;
factory.list = [];
this.update = function(restUrl) {
return $http.get(restUrl)
.success(function(data){
factory.list = data;
})
.error(function(data){
console.log('Error: ' + data);
});
};
this.add = function(formData, restUrl){
$http.post(restUrl, JSON.stringify(formData))
.success(function(data){
console.log('Success: ' + data);
})
.error(function(data){
console.log('Error: ' + data);
});
};
this.remove = function(value, restUrl){
// get index of clicked object
var index = this.protocolList.indexOf(value);
// Remove object with given index from array
factory.list.splice(index, 1);
var url = restUrl + value.id;
// delete it from DB
$http['delete'](url);
console.log('Deleted object with ID ' + value.id);
};
// Change existing object
this.change = function(value, restUrl) {
// get index of clicked object
var index = this.protocolList.indexOf(this.activeObject);
var url = restURL + value.id + '/' + value.name;
console.log('url: ' + url)
// change it before store it to DB
$http['put'](url);
console.log('Changed object with ID ' + this.activeObject.id);
};
}
和我使用工厂的控制器
/*
PROTOCOL CONTROLLER
*/
function protocolController(asyncFactory){
var controller = this;
controller.list = asyncFactory.list;
controller.formData = {};
this.getUpdatedList = function() {
asyncFactory.update('../protocols')
.then(function(data){
controller.list = data;
});
};
this.addData = function(formData){
asyncFactory.add(formData, '../protocols');
};
this.removeData = function(value){
asyncFactory.remove(value, '../protocols');
};
this.editData = function(value){
asyncFactory.change(value, '../protocols')
}
}
然后这样称呼它:
/*
MAIN - WHERE THE CONTROLLER AND FACTORY IS CALLED
*/
var app = angular.module('TransactionMonitoring', [])
.controller('protocolController', protocolController(asyncFactory));
【问题讨论】:
-
你的工厂对我来说更像是一个服务(工厂被调用并返回一些东西。服务使用 new 实例化)。我还建议阅读John Papas styleguide 并将其中的一些内容应用到您的代码中(使用数组语法的依赖注入、命名函数而不是匿名函数、getter/setter 语法而不是 var app...)
-
我按照我的做法更新了你的代码。
标签: javascript angularjs refactoring factory