Javascript 在AngularJS中发送包含子对象的JSON数据
我想发一个这样的帖子Javascript 在AngularJS中发送包含子对象的JSON数据,javascript,angularjs,json,Javascript,Angularjs,Json,我想发一个这样的帖子 { "title": "sample string 2", "comment": "sample string 5", "child": { "name": "sample string 2" }, "children": [ { "name": "sample string" }, { "name": "sample string"
{
"title": "sample string 2",
"comment": "sample string 5",
"child": {
"name": "sample string 2"
},
"children": [
{
"name": "sample string"
},
{
"name": "sample string"
}
]
}
我正在发送这个
{
"title": "sample string 2",
"comment": "sample string 5"
}
用这个
(在控制器中)
有了这个资源工厂
myApp.factory('Product', function ($resource) {
return $resource('http://api.com/api/product/:id', { id: '@id' }, {
update: {
method: 'PUT'
}
});
});
以上工作。我的问题是,如何更改上述代码,以便发送子对象,如上图所示
我试过了
vm.product.child.name = "my new child"
但是运气不好。创建一个包含所需信息的对象,然后指定:
var child = { "name" : "my new child" };
vm.product.child = child;
您不能直接分配给var.product.child.name
,因为此时没有可分配的子项-一旦分配了vm.product.child
,就可以向其添加字段。事实上,这也会起作用:
vm.product.child = {};
vm.product.child.name = "my new child";
如果您想要一个子数组:
vm.product.children = [];
var child = {"name":"my child name"};
vm.product.children.push(child);
将
vm.product.children
的值设置为一个数组后,您可以根据需要推送任意多的子数组。啊,是的,这很有效。很简单:)但是,我该如何生成子对象,即包含对象的数组?
vm.product.children = [];
var child = {"name":"my child name"};
vm.product.children.push(child);