Greetings! I am fairly new to AngularJS and currently grappling with a concept...
Essentially, I have a form that can accommodate 1 to many "Guests" for an event. By utilizing ng-repeat, I showcase the fields in this manner:
<div ng-repeat="guest in guests">
<input type="text" ng-model="guests[$index].first_name" />
<input type="text" ng-model="guests[$index].last_name" />
<select ng-model="guests[$index].meal" ng-options="meal.id as meal.name for meal in meals"></select>
<select ng-model="guests[$index].rsvp">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div class="controls"><button ng-click="submit()" class="btn btn-success">Save</button></div>
Furthermore, in the controller:
//DETERMINE TOTAL IN PARTY
var totalInParty = 2;
$scope.meals = RSVPRes.Meals.query();
//EDIT
if ($scope.rsvpId) {
}
//NEW RSVP SUBMISSION
else {
$scope.rsvp = new RSVPRes.RSVP();
//INITIALIZE EMPTY GUESTS
$scope.guests = [];
for (var i = 0; i < totalInParty; i++) {
$scope.guests[i] = {
first_name: '',
last_name: '',
meal: 1,
rsvp: 0
};
}
}
Moreover, here is my Resource setup:
.factory( 'RSVPRes', function ( $resource ) {
return {
RSVP: $resource("../reservations/:id.json", {id:'@id'}, {'update': {method:'PUT'}, 'remove': {method: 'DELETE', headers: {'Content-Type': 'application/json'}}}),
Meals: $resource('../meals.json')
};
})
Everything seems to be functioning smoothly, however, saving the data poses a challenge. My aim is to save each Guest's details (First Name, Last Name, Meal & RSVP) as individual rows.
When attempting the following:
$scope.submit = function() {
for(var i = 0; i < $scope.guests.length; i++){
$scope.rsvp.first_name = $scope.guests[i].first_name;
$scope.rsvp.last_name = $scope.guests[i].last_name;
$scope.rsvp.meal_id = $scope.guests[i].meal;
$scope.rsvp.rsvp = $scope.guests[i].rsvp;
$scope.rsvp.$save();
}
$state.transitionTo('rsvps');
};
This results in creating two rows (with total_in_party set to 2) but always containing the data of the second person.
I feel like I'm on the right track, I've explored several ng-repeat examples but none seem to address my specific scenario!
Any assistance would be greatly appreciated.
SOLVED
I had made an error in my approach towards the Resource, by creating a new RSVP object every time within the loop.
$scope.submit = function() {
for(var i = 0; i < $scope.guests.length; i++){
$scope.rsvp = new RSVPRes.RSVP();
$scope.rsvp.first_name = $scope.guests[i].first_name;
$scope.rsvp.last_name = $scope.guests[i].last_name;
$scope.rsvp.meal_id = $scope.guests[i].meal;
$scope.rsvp.rsvp = $scope.guests[i].rsvp;
$scope.rsvp.$save();
}
$state.transitionTo('rsvps');
};