2013-02-10 49 views
0

我有一個與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>' 
    }; 
    }); 
+0

您可以發佈一些代碼嗎?這樣的問題將在具體而不是抽象中得到更好的回答。 – 2013-02-10 20:47:21

回答

1

怎麼樣包裝將您的整個API ping到一個服務並從控制器訪問它?您可以將資源類型作爲參數傳遞給函數

+0

你是對的。服務實際上就是「模型」,如果我將所有方法放入服務中,則將其作爲對象導出,並將該類型傳遞給服務。這種方式服務是可重用的,而不是控制器。感謝給我推我需要解決這個問題。 – kimpettersen 2013-02-10 22:59:50