AngularJS Automatically Syncing Data between Server and Client

vilijou picture vilijou · Mar 14, 2013 · Viewed 24k times · Source

There's something in the AngularJS docs that I can't seem to find or maybe I'm just missing.

I'm creating a web app with NodeJS and Express in the back-end and I'm trying to understand how it can interact with Angular in the front end. In particular, I'll have a JSON API for Angular to fetch the information from. I want for the front end to always be up-to-date.

My questions are:

  • Does the two-way data binding feature mean Angular ($resource or $http) automatically fetches the data from the server every n seconds?
  • Does it naturally use long polling, short polling or websockets?
  • Do you need JQuery to achieve the server-client syncing or can everything be done with Angular?
  • Do you have to add extra code to make this behavior happen? Do I need to use $timeout?

Every example I seem to find involves the client fetching the data once. Not syncing the data with the server.

Answer

eterps picture eterps · Mar 14, 2013

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).