Connect your AngularJS application to Firebase

Connecting angularjs to firebase

AngularJS by default provides a two way data binding between your view and controller. By connecting a real time database like Firebase you can extend the two way data binding to three way data binding. So if there is any changes in any one of the model, view or database, the updated content will be displayed on the other two at real-time. Lets see how we can connect out Angular application to the firebase database.

1. You don’t need to install anything to use firebase. Just create a free account on there website to begin. After you have successfully signed up and logged in, firebase will create a new firebase app for you by default. Each app that you create inside firebase has got a unique URL which will be ending with firebaseio.com. For example, https://test-app-453.firebaseio.com/. This URL is used for authentication of users and saving & retrieving data.

NOTE: AngularFire is used to connect the AngularJS to firebase. You can click here to know more about AngularFire.

2. We need to add certain scripts like angularjs, firebase and angularfire in our application to successfully connect the angular application to the firebase.

https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js
https://cdn.firebase.com/js/client/2.2.4/firebase.js
https://cdn.firebase.com/libs/angularfire/1.1.2/angularfire.min.js

You can either use these scripts via cdn or can use npm or bower to download them.

3. After including all the dependency files, the next step is to add the ‘firebase’ module in our application so that the services such as $firebaseObject, $firebaseArray and $firebaseAuth which are provided by firebase module can be made available inside our controllers, services and factories.

var fireApp = angular.module("mainApp", ["firebase"]);
app.controller("MainCtrl", function($scope, $firebaseObject) {
  var dataRef = new Firebase("https://test-app-453.firebaseio.com/");

  $scope.data = $firebaseObject(dataRef);
// save the data inside scope.
});

4. To setup the three way data binding between your DOM, JavaScript and Firebase we will use the $firebaseObject service to create a synchronized object and bind it with the $scope variable using the $bindTo() method.

app.controller("MainCtrl", function($scope, $firebaseObject) {
  var dataRef = new Firebase("https://test-app-453.firebaseio.com/");

/* the data from the firebase will be saved inside the localObject variable */
var localObject=$firebaseObject(dataRef);

/* use the $bindTo() method to do a three way data binding between localObject, $scope and firebase */
  localObject.$bindTo($scope,"data");
// save the data inside scope.
});

Related Posts