Stripping out elements when sending an using AngularJS $http

I’m increasingly using AngularJS for frontend stuff to shift as much as possible into the browser. Basically it just receives some JSON, processes it and then sends it back to be stored in the database. However often to reduce the number of round-trips to the server you want to include additional data with the response. For example if you have a table of foods and you want to form a list of them in Angular, one way would be to get the list of ID’s and then fetch them either one-by-one or in bulk, however this is obviously not good for responsiveness or the backend server. So you’d typically want to send an array of rows from the server but for saving again, effectively you only actually need the ID’s as the rest of the data is already on the server. When you are dealing with big lists this can be rather annoying. Here’s an easy way to strip out keys on AngularJS before sending to the server:

This overrides the $http.defaults.transformRequest as it basically does the same thing (using Angular’s toJson function). It would be nice if it were possible to just use toJson but specify a function for the json transformation.

Leave a Reply

Your email address will not be published. Required fields are marked *