2

I am starting to build a web application.

The user can select and add items to a list of fruit. The list of fruit objects is stored in an array in Javascript/AngularJS.

When the user presses the Submit button, I want the entire list of fruit to be sent to the server, where the list is then saved into a database.

I have only a basic understanding of HTTP. Would I want to POST the array? How would I do this?

1
  • 1
    Yes, you'd want to post the array. Look at $http provider. Commented Feb 14, 2015 at 18:45

2 Answers 2

0

I'd prefer you to go for $resource which includes in ngResource module.

While passing array inside your post call you need to mention isArray option to true inside $resource option

CODE

angular.module('app',[])
//factory will have resource object
.factory('myService',function($resource){
  var postFruitData = function(){
    return $resource('/savefruit', {}, {saveData: {method:'POST', isArray: true}});
  }
  return{
    saveData: postFruitData
  }
})
.controller('mainCtrl',function($scope,myService){
   //this function needs to be call on post like form ng-submit
   $scope.postFruitData = function(){
     myService.saveData({}, $scope.data).$promise.then(function(data){
        //you will get data here
     });
   }
});

For more info you can also take look at this SO Question

Hope this could help you. Thanks.

Sign up to request clarification or add additional context in comments.

Comments

0

Here's a POST example that posts an array of fruit to the server. This code would be located inside your button click function.

$scope.fruit = [{name: 'Apple'}, {name: 'Grape'}];

// Simple POST request example (passing data) :
$http.post('/someUrl', {fruit: $scope.fruit}).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
   // called asynchronously if an error occurs
   // or server returns response with an error status.
  });

Take a look at the angular documentation for $http. This should help you out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.