0

我有一个与 REST API 通信的 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>'
    };
  });
4

1 回答 1

1

将整个 API 包装到服务并从控制器访问它怎么样?您可以将资源类型作为参数传递给函数

于 2013-02-10T21:53:50.373 回答