Sending array to server in AngularJS - angularjs

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?

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.

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.

Related

How can I parse this JSON response

I have the following JSON data being received by angularJS. It's being brought in from an ArrayList using a get request.
0: Object
id:1
area: "State"
gender: "Both"
highestEd: 3608662
.... etc
1: Object
id:2
area: "State"
gender: "Both"
highestEd: 3608662
.... etc
However I can't figure out how to access it using either a controller or the UI. I want to be able to store this data in Angular so I can then create graphs using the information. The only way I know it's definitely there is through looking at the response in firefox.
Any help / advice would be greatly appreciated.
Your JSON data is not in proper format. Use JSON lint to check
Use $http.get('/get_url/') to get the response . One sample example for this.
Once you have response in $scope.yourVariable use ng-repeat to loop over it
Take a look at this fiddler here you might get some ideas.
After calling the API using $http from you factory you will have resolve the data that you are getting. The controller needs to call the API method and then bind the resolved data from your factory to the API.
Factory
myApp.factory("Data", function($q, $http) {
return {
getData: function() {
var deferred = $q.defer();
/* --Actual API Call
$http.get("/url")
.then(function(response) {
deferred.resolve(response.data);
})
*/
//Dummy Data
var data = m;
deferred.resolve(data);
return deferred.promise;
}
}
});
Controller
function MyCtrl($scope, Data) {
Data.getData()
.then(function(items) {
$scope.bobs = items;
console.log($scope.bobs);
})
}
Replace the dummy data initialization from factory to the actual API call.

How to display response data ($http) from server in AngularJS

How to display reponse data (get) from server in AngularJS
in my code I need to alert $scope.orders inside that controller but it willll not show..
function OrderController($scope,$http)
{
var orderPromise = $http.get("../api/order");
orderPromise.success(function(data, status, headers, config)
{
$scope.orders=data
alert(JSON.stringify($scope.orders)) // First alert
});
orderPromise.error(function(data, status, headers, config)
{
alert("Error");
});
alert(JSON.stringify($scope.orders)) // Second alert
}
How can i access $scope.orders to outside the success fun()
Here I am alerting $scope.data in two times
In here First Alert is shown
but Second Alert is nothing to show why?
How to show second one?
Second alert will not show because there's nothing in $scope.orders when you alert it. That's the nature of asynchronous calls, only when you enter the success/error sections will you have something there (or not...).
Until the server returns your response and the success/error functions trigger, that variable is still unpopulated since $scope.orders=data hasn't run.
You should read the docs for some more info, and get some deeper understanding into how promises work.

How to process data in controller once received in angularjs?

Assume I have a directive that contains a form where a user can enter in the name of a fruit.
I have a FruitFindController. User enters fruit name, "Apple", clicks a button which submits to controller.
Controller calls a service "GetFruitInfo(fruit)" and passes in "Apple" as parameter.
Once the information is received, it should call a method "addToListAndDoStuff()" in order to add the fruitinfo to the list.
My issue is, in my FruitFindController (assume fruitFinder is the service)...
$scope.GetFruitInfo = function() {
$scope.foundFruit = fruitFinder.GetFruitInfo($scope.fruitField);
// should alert "Found Fruit" and call addToListAndDoStuff() method to add the foundFruit information to the list managed by another directive, "FruitList".
}
What is the best way to "wait for the information is stored into $scope.foundFruit before doing any code below and popping up the alert box?
The best way is to use a promise. In your fruitFinder service, the GetFruitInfo method would look something like this..
function GetFruitInfo(fruit) {
var delay = $q.defer();
$http({method: 'GET', url: 'http://myapi.com/getFruitInfo?fruit=' + fruit}).
success(function(data, status, headers, config) {
delay.resolve(data);
}).
error(function(data, status, headers, config) {
delay.reject(data);
});
return delay.promise;
}
This method returns a promise object that you can wait for it to resolve in your controller using the .then() method, like this..
$scope.GetFruitInfo = function() {
$scope.foundFruit = fruitFinder.GetFruitInfo($scope.fruitField).then(function(response) {
alert('Found Fruit');
addToListAndDoStuff(response);
});
}

Angular.js - How to pass data from controller to view

This is the first time i am using Angular.js. So my workflow could be wrong.
How do i pass data from controller to the view
ng-view -> Displays html page using jade
When user clicks on submit button, i use $http on the controller and submit the request to the server.
The server returns me the necessary data back which i need to pass to another view.
My code snippet
function TrackController($scope,$http,$location,MessageFactory){
$scope.message = MessageFactory.contactMessage();
$scope.submit = function () {
var FormData = {
'track_applicationid': $scope.track_applicationid,
'track_email': $scope.track_email
}
$http({method: 'POST', url: '/track', data: FormData}).
success(function(data, status, headers, config) {
$scope.registeredDate = 'data.REGISTERED_DATE';
$scope.filedDate = data.FILED_DATE;
$location.path('trackMessage');
}).
error(function(data, status, headers, config) {
console.log('error');
});
}
}
In the above code, i want to pass registeredDate and filedDate to trackMessage view.
After going through the comments, i understood you are using one controller for two views.
If you want to set values to $scope.registeredDate and $scope.filedDate, You have to declare those objects globally using root-scope(Not recommended) or
use Angular values.
I recommended to use two different controllers.

use promise to get only portion of ajax response

The tutorial and docs show this very convenient syntax for AJAX calls:
$scope.myvar = $resource(/*blah blah*/);
Is there a way to use this syntax (instead of having to create a new successfn every time) if my API doesn't return myvar but something like {"myvar": myvar}?
UPDATE: Ah, now I think I got what you're after: You want to have the empty reference (placeholder) for a field of the returned object, in a call like this:
var User = $resource('/user/:userId', {userId:'#id'});
Am I right?
If so - I think the easiest way is simply to bind to the object's field (aka {{user.myvar}}).
Well, the success function is called only once (and if) the data has been received successfully. The function is called with the fetched data given to it as an argument and you can access it no matter its structure. You can reuse a function instead of defining one inline, of course.
So instead of this (example from Angular docs):
$http({method: 'GET', url: '/someUrl'}).
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.
});
You can use:
function myHandler(data) {
// Do something with data.myvar ...
}
$http({method: 'GET', url: '/someUrl'}).success(myHandler);
Hopefully this helps, but very possibly I did not get what exactly you're after :) Let me know.
Relevant documentation.
You need to call get() or query() on your resource to make an actual AJAX request. If you don't want to assign the full result of the server API directly to some ($scope) variable, then you have to write the success function.
var SomeResource = $resource('/blah/blah');
var theResource = SomeResource.get({optional params here}, function() {
$scope.myVar = theResource.myVar;
}
or
var SomeResource = $resource('/blah/blah');
SomeResource.get({optional params here}, function(theResource) {
$scope.myVar = theResource.myVar;
}
Or do what #Chasseur recommends -- assign the full result then bind to the appropriate field in your view:
var SomeResource = $resource('/blah/blah');
$scope.theResource = SomeResource.get({optional params here});
Then in HTML use {{theResource.myVar}}.
Also, $resource, unlike $http, does not return a promise. Update: in newer versions of Angular, $resource now exposes a promise.

Resources