在Angularjs中将控制器中的JSON和参数传递给Factory

时间:2016-05-16 21:14:32

标签: angularjs json factory ngresource

我有一个工厂,我用它来更新我的休息服务中的数据。如果我硬编码其中的id更新就好了,如果我尝试用我的json文件传递一个paremeter,json将被传递给其他服务但是paremeter没有被传递到工厂所以我的restUrl不是& #39;正确生成,因为它缺少itemId。

工厂:

angular.module('myApp')
  .factory('updateItem', function ($resource) {

      return $resource('http://someserviceUrl/items/:itemId', {}, {
        update: {method: 'PUT', params: {itemId: '@itemId'}}
      });


  });

控制器:

    $scope.itemId = 21;
    var itemData = {"orderItem":  {"itemHdr": {
          "itemId": "",
          "itemDescription":"Item Description",
          "typeCd": "someType",
          "salesPgm":"thisProgram",
          "onSale": true
        }
};

  updateRfp.update($scope.itemData,$scope.itemId)
    .$promise.then(function(res) {
    console.log('updateItem.update triggered!');
    $scope.results = 'Item '+ res.code + ' has been saved.';


  });

我没有正确传递itemId吗?我读过的文档显示了这种在控制器和工厂之间传递变量的方法,但是在你做json和参数的组合时它并没有显示如何做。

1 个答案:

答案 0 :(得分:1)

Angular docs

// Now call update passing in the ID first then the object you are updating
Notes.update({ id:$id }, note);

所以看起来你应该将Id作为对象和交换参数传递