Search code examples
angularjsangularjs-scopeangularjs-ng-repeatangular-ngmodel

multiple forms ng-repeat - posting back the current $scope only, not whole object


I have multiple forms using ng-repeat.

<div ng-repeat="individual in orderDetails track by $index">
    <form ng-submit="saveDetails();">
      <input ng-model="individual.order.statusText">
      <button type="submit">Save changes</button>
    </form>
</div>

Here's an example of what's stored in my object, for each individual (IE - object) in OrderDetails.

orderDetails {
    object{
        foo {},
        bar {},
        order {}
    },
    object{
        foo {},
        bar {},
        order {}
    }       
}

Now I'm referencing the data with individual in my repeater, how can I submit only the order from a single individual when posting back to the server, as opposed to the whole orderDetails object?

Here is my save function, for the form submit button

$scope.saveDetails = function(data, status) {               

    ordersService.updateOrder($scope.orderDetails.individual.order)

    // once submitted update the whole model on the page again
    .success(function(data, status) {                   
        $scope.orderDetails = data;                 
    })                         
}

And here is my service:

getData.updateOrder = function(data){
    var url = '/service/rest/orders';

    return $http.post(url, data)                    

    .error(function (data, status, headers, config) {
        console.error('Error fetching feed:', status, headers, config);
    });
};            

return getData; 

Thanks again for any help.


Solution

  • Simple, pass the individual object into the submit handler, eg

    $scope.saveDetails = function(individual) {
        ordersService.updateOrder(individual.order).success(function(data) {
            $scope.orderDetails = data;
        });
    };
    

    and in your HTML

    <form ng-submit="saveDetails(individual)">
    

    To override the individual order with the new data, you could just write it back into individual, eg

    .success(function(data) {
        angular.extend(individual, data); // or angular.merge for deep extending
    });