我有一個與REST API通信的Angular JS應用程序。該應用程序有一個管理部分,可讓用戶創建,讀取,更新和刪除資源。可重複使用和可測試代碼的代碼結構Angular JS
有幾種不同的資源,每個資源一個部分,我將每個成員定義爲某種輸入字段。我創建了一個指令,爲模板共同創建了一個雙向綁定。
我也爲我的每個資源創建了一個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>'
};
});
您可以發佈一些代碼嗎?這樣的問題將在具體而不是抽象中得到更好的回答。 – 2013-02-10 20:47:21