AngularFire

When we talk of building any system, we either have to deal with objects, or with collections. Those objects often contain collections, for example, in a one-to-many relationship. So, AngularFire gives us two different services—$firebaseObject and $firebaseArray—to synchronize objects and arrays with the backend. Let’s see how to use each of these services in the following examples.

Synchronized arrays with $firebaseArray()

So, here’s our index.html file (just the relevant part of the code is shown):

<script src="https://cdn.firebase.com/js/client/2.2.3/firebase.js">
</script>
<script src="https://cdn.firebase.com/libs/angularfire/1.0.0/angularfire.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js">
</script>

(dunebook\sync-objs-arrays\index.html)

We are referring to firebase, angularfire, and the Underscore (http://underscorejs.org/) libraries from the CDNs. In a real-life scenario, we would have installed them in our application using 'bower' and referred to these libraries from their local paths.

Here’s the main module of the application:

var app = angular.module('firebaseApp', [
  'ngRoute',
  'firebase'
]);

// this is the Firebase URL we'll be talking to
// in case of your Firebase account, please modify
// the below URL appropriately
app.constant('FIREBASE_URI', 'https://society.firebaseio.com/');

app.config(function ($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'main.html'
    })
    .when('/arrays', {
      templateUrl: 'sync-array/syncarray.tpl.html',
      controller: 'SyncArrayCtrl'
    })
    .when('/objects', {
      templateUrl: 'sync-object/object.tpl.html',
      controller: 'SyncObjectCtrl'
    })
    .when('/properties', {
      templateUrl: 'property/property.tpl.html',
      controller: 'PropertyCtrl'
    })
    .otherwise({
      redirectTo: '/'
    });
});

(dunebook\sync-objs-arrays\app.js)

Advertisements