Search code examples
angularjsangular-resource

How to send objects with arrays using angular resource?


I have a product object with a property called category_ids that is an array of ids.

I've added an $update method to my resource factory so I can send a PUT request.

When I PUT, the server receives data that looks like:

id: 1,
description: 'Yada yada',
category_ids: [1,2,3],
product: { id: 1, description: 'Yada yada' } //<-- I need category_ids in here

How can I get the category_ids array into the product node there?


More detail:

I'm just using angular's resource to update:

'use strict'

angular.module('myApp').factory 'Product', ($resource) ->

  resource = $resource '/api/v1/products/:id', { id: '@id' },
    update:
      method: 'PUT'

  return resource

Interestingly, this problem only happens with calling instance methods on my object. Calling the class methods on the factory itself works:

currentProduct.$update() <-- This does not give me the format I want!

Product.update(id: currentProduct.id, product: currentProduct) <-- This does :-\


Solution

  • You can add properties to $resource object like

    currentProduct.category_ids = [1,2,3];
    

    Now this property becomes request parameter for PUT request.

    Lets suppose you have $resource factory name "Product" then following code will work for you

      var currentProduct = new Product()
    
        // Bind properties to resource object
        currentProduct.id = 1
        currentProduct.description = 'Yada yada'
        currentProduct.category_ids =  [1,2,3]  
    
        // Initiate PUT request.
        currentProduct.$update()