我有一个Angular JS应用程序,它正在与REST API通信。该应用程序有一个管理部分,用户可以创建、读取、更新和删除资源。
有几个不同的资源,每个资源一个部分,我将每个成员定义为某种类型的输入字段。我创建了一个指令,为模板的常见内容创建双向绑定。
我还为我的每个资源创建了一个ngResource。
现在来谈谈我的问题。我有一个资源的控制器在工作,它大多只包含直接从部分调用的函数(例如submit()),并与ngResource通信。
除了少数例外,代码本身可以复制到所有其他控制器,只需更改资源名称。这就是我想要避免的。
我如何创建一个抽象的ParentCtrl并以某种方式注入当时所需的资源?这是可测试的吗?这是解决问题的糟糕方法吗?
通常,我会尝试抽象一个模型而不是控制器,但在这种情况下,我真的看不出该怎么做。
编辑:添加代码
资源:
angular.module('experienceServices', ['ngResource'])
.factory('Experience', function($resource){
return $resource('/api/experience/:id',
{'id': '@_id'}, {edit: { method: 'PUT' }});
});
控制器:
App.controller('ExperienceCtrl', function( $scope, Experience ) {
$scope.resources = [];
$scope.currentItem = {};
$scope.updateResources = function(){
$scope.resources = Experience.query();
};
$scope.findById = function(id){
for (var i = 0; i < $scope.resources.length; i++){
if ($scope.resources[i]._id === id){
return $scope.resources[i];
}
}
};
$scope.showItem = function(id){
$scope.currentItem = findById(id);
};
$scope.create = function (experience){
Experience.save(angular.copy(experience), function(){
$scope.updateResources();
});
};
$scope.editItem = function (experience){
var item = angular.copy(experience);
if (!item.hasOwnProperty('_id')){
alert('Can not modify non existing item');
}
Experience.edit(item, function(res){
$scope.updateResources();
});
};
$scope.edit = function(id){
$scope.experience = $scope.findById(id);
};
$scope.del = function(id){
Experience.remove({ id: id }, function(){
$scope.updateResources();
});
};
$scope.updateResources();
});
指令:
App.directive('resources', function (){
return {
scope: {
list: '=',
display: '@',
edit: '&',
del: '&'
},
template: '<div ng-repeat="elem in list">Name: {{ elem[display] }}' +
' <button ng-click="edit({ item: elem._id })">Edit</button> ' +
' <button ng-click="del({ item: elem._id })">Delete</button> ' +
'</div>'
};
});
将整个API包装到服务并从控制器访问它怎么样?您可以将资源类型作为参数传递给函数