简体   繁体   中英

Angular ng-model send data as array to rails-api

When adding the ng-model directive to an HTML element, I usually do so with it attached to an object. However, before sending the HTTP request, a portion of the data should be an array of objects.

In my rails-api I have a User model and an Address model. The user has many addresses and the address belongs to a user.

The goal is to just take in the parameter via strong params and save each of the addresses (received as JSON, array of objs) and have them each be related to the user.

Currently, i'm numbering them and doing some extra manipulation prior to shipping the data off to the API. Ex:

<input type="text" ng-model="form.address1">

And then for the second, ng-model="form.address2" .

How can I setup an array of objects using the ng-model attribute and add objects onto the array in my HTML?

You can bind to array too:

<input type="text" ng-model="form.address[0]"> Address 1
<input type="text" ng-model="form.address[1]"> Address 2

Demo: http://plnkr.co/edit/owpAqLLlgOjBKfqHSZ4U?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM