我有一个小应用程序,它使用三个状态(使用ui-router)创建和编辑费用:index,new,edit。新的和编辑相同的功能几乎相同,所以不是让代码两次,我想将其外包给服务。问题是当我尝试在newCtrl或editCtrl中更改绑定到$ scope的变量时。例如,两者都具有此功能:
$scope.removeFeeRule = function(){
$scope.feeParameter = null;
$scope.feeRule.multiplier = null;
$scope.feeRule.addend = null;
$scope.feeRule.fee_suite_id = null;
$scope.feeRule.fee_parameter_id = null;
}
如何避免此代码重复并将其移至服务中?
答案 0 :(得分:1)
管理费用的简单服务。我更喜欢删除设置为空值。我也不想在服务中公开我的对象,所以我通常会添加get
来访问数据。如果您真的想要,可以公开FeeService.myFee
vs FeeService.getFee()
angular.module('yourmodule')
.service('FeeService', FeeService)
.controller('MyController', MyController);
function FeeService(){
this.reset = reset;
this.getFee = getFee;
var _currentFee = {};
function getFee(){
return _currentFee;
}
function reset(){
delete _currentFee.feeParameter = null;
delete _currentFee.multiplier = null;
delete _currentFee.addend = null;
delete _currentFee.fee_suite_id = null;
delete _currentFee.fee_parameter_id = null;
return _currentFee;
}
}
function MyController($scope, FeeService){
$scope.removeFeeRule = removeFeeRule;
init();
function init(){
$scope.myFee = FeeService.getFee();
}
function removeFeeRule(){
FeeService.reset();
}
}