Programing & Development

Talking to Servers using AngularJS – Overview

Talking to Servers in AngularJS

Real apps generally talk to real servers. Mobile apps and the emerging Chrome desktop apps may be exceptions, but for everything else, whether you want persistence in the cloud or real-time interactions with other users, you probably want your app to talk to a server.

For this, Angular provides a service called $http. It has an extensive list of abstractions that make it easier to talk to servers. It supports vanilla HTTP, JSONP, and CORS. It includes security provisions to protect from both JSON vulnerabilities and XSRF. It lets you easily transform the request and response data, and it even implements simple caching.

Let’s say we want to retrieve products for our shopping site from a server instead of from our silly in-memory mocks. As its just an overview of how to communicate with servers, so let’s imagine that we’ve created a service that will return a list of products as JSON when you make a query to /products.

Given a response that looks like this:

“id”: 0,
“title”: “Paint pots”,
“description”: “Pots full of paint”,
“price”: 3.95
“id”: 1,
“title”: “Polka dots”,
“description”: “Dots with that polka groove”,
“price”: 12.95
“id”: 2,
“title”: “Pebbles”,
“description”: “Just little rocks, really”,
“price”: 6.95

we could write the query like so:

function ShoppingController($scope, $http) {
$http.get(‘/products’).success(function(data, status, headers, config) {
$scope.items = data;

and use it in a template like this:

<body ng-controller=”ShoppingController”>
<tr ng-repeat=”item in items”>
<td>{{item.price | currency}}</td>

It was just an overview and we can’t get into details in these type of articles. For details and reference, here are few links: