AngularJS Automatically Syncing Data between Server and Client

Two-way binding in AngularJS refers to the data model ($scope) and your view (directives). For instance, if the data changes in your model, the view will automatically update. Likewise, if the user modifies data in the view, your model will automatically update.

Interacting with web services is conducted via the $http service module. So to get data from your RESTful API, you would do something like:

$http.get('/someUrl').success(successCallback);

Full documentation for $http is on the AngularJS site. I think you will find it is very similar to jQuery’s $.ajax methods. You easily set up $http.get() for short-polling with angular’s $timeout service (basically a wrapper for setTimeout).

For real time updates between the AngularJS client and the server API, you might want to look into Socket.io. It uses node.js to create a live socket connection between the browser and the server, and has fallback mechanisms (flash, long-polling) for older browsers. There is a boilerplate project on GitHub that demonstrates how to set up AngularJS with Socket.io:
https://github.com/btford/angular-socket-io-seed

To Recap:

Does the two-way data binding feature mean Angular ($resource or
$http) automatically fetches the data from the server every n seconds?

No, two-way binding is between Angular models and views.

Does it naturally use long polling, short polling or websockets?

Angular does not include any of these by default. You must set them up yourself.

Do you need JQuery to achieve the server-client syncing or can everything be done with Angular?

$http is, in a broad sense, the Angular equivalent of jQuery’s $.ajax

Do you have to add extra code to make this behavior happen? Do I need to use $timeout?

Use $timeout for short-polling, or roll your own solution for long-polling and/or websockets (see the angular-socket-io-seed project).

Leave a Comment