2

I want to send a POST like this;

{
  "title": "sample string 2",
  "comment": "sample string 5",
  "child": {
    "name": "sample string 2"
  },
    "children": [
        {
            "name": "sample string"
        },
        {
            "name": "sample string"
        }
    ]
}

I am currently sending this

{
  "title": "sample string 2",
  "comment": "sample string 5"
}

using this (in the controller)

vm.product = new Product();
vm.product.title = "My title";
vm.product.comment = "my comment";

with this resource factory

myApp.factory('Product', function ($resource) {
    return $resource('http://api.com/api/product/:id', { id: '@id' }, {
        update: {
            method: 'PUT'
        }
    });
});

The above works. My questions is, how would i change the above code, so i can send child objects, as seen in the top?

I tried with

vm.product.child.name = "my new child"

But with no luck.

1 Answer 1

2

Create an object with the information you want in it, then assign that:

var child = { "name" : "my new child" };
vm.product.child = child;

You can't assign directly to var.product.child.name because, at that point, there is no child to assign to - once you have assigned vm.product.child, you can add fields to it. In fact, this would also work:

vm.product.child = {};
vm.product.child.name = "my new child";

If you want an array of children:

vm.product.children = [];
var child = {"name":"my child name"};
vm.product.children.push(child);

Once you have set the value of vm.product.children to an array, you can push as many children as you want to it.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah yes, that works. So simple :) But, how would i make the children, that is an array with objects?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.