Build Better Software

Using Firebase and AngularJS to Make Real-Time Applications

Real-time applications are nothing new, however we have only recently seen them used in applications that we use on a daily basis. Users have been exposed to the user experiences that real-time technology provides, and are now demanding those experiences in apps they use.

by Cat Buckley

The leading social platforms like Facebook and Twitter are all built upon real-time web technologies. They represent one of the main ways we communicate with one another. Real-time powers the instant notifications and updates that are a major part of what makes them so popular.

But real-time isn't limited to only displaying data as soon as it's available. It shows its real power when used with interactive experiences in which users and systems can instantly communicate with one another. Industries are quickly discovering the benefits of real-time apps.

Firebase makes building and rapid-prototyping these kinds of applications simpler by letting you focus on how the application should behave and look, without getting bogged down in the more tedious parts of real-time development. This means you get a faster turn-around and a more solid product in the end.

Note: This post assumes you have some previous knowledge about HTML, Javascript, and AngularJS. Not sure what I'm talking about? Check out Codecademy to get started learning for free and Shaping Up with AngularJS. Have a larger project that you want expert assistance with? Drop us a line and see how we can help.

What is Firebase?

Firebase is not your grandaddy's database. It's a complete real-time, scalable backend. It provides all the tools needed to build rich, collaborative applications using only client-side code. Firebase applications can be built rapidly and provide real-time updates out-of-the-box.

Where does it fit?

Firebase can serve anything ranging from rapid prototyping to fully blown production applications. Apps can consist of only client-side code, relying 100% on Firebase's backend, or Firebase can communicate with custom server-side code.

Firebase is so flexible, it can even be used to implement new features in existing apps that never used any Firebase code before. It can easily fit in at any stage of development. More information is available on Firebase's blog.

Getting started

In this post, we will be focusing on building a simple ToDo app using only client-side code. For our purposes, we can have Firebase handle all of our back-end heavy lifting.

Upon completion, users of the ToDo app will be able to add new items, remove old items, and update the status of each item. The app will also be real-time, meaning that changes will be synced across browsers automatically without the need for a page refresh. The first step is to set up a Firebase application.

Just want to see the code? Check out this project on GitHub.

Create an account

First, start by creating a new Firebase account. The Hacker plan is free for up to 50 connections, 100MB of storage, and 5GB of transfer. Once you set up your account, a new Firebase app will be created and given its own URL ending in firebase.io. This URL will be used to authenticate users, and store and sync data with AngularFire.

Add dependencies

Starting an AngularFire project requires three dependencies: Angular.JS, Firebase and the AngularFire libraries. Include these script tags in the head.

Inject services

In your JavaScript file, inject the AngularFire services by registering firebase as a module in the application.

var todoApp = angular.module('TodoApp', ['firebase']);

todoApp.controller('TodoCtrl', ['$scope', '$firebaseArray',
    function($scope, $firebaseArray) {
        
}]);

Now $firebaseObject, $firebaseArray, and $firebaseAuth services are available to be injected into any controller, service, or factory.

Connect to the database and initialize ToDo array

Connecting to the database first requires creating a firebase reference. In this case, we named it todosRef. Next, we will get the list of existing ToDo items as an array (there will be no ToDo items returned yet since we have not created any).

var todoApp = angular.module('TodoApp', ['firebase']);

todoApp.controller('TodoCtrl', ['$scope', '$firebaseArray',
    function($scope, $firebaseArray) {
        
    // CREATE A FIREBASE REFERENCE
    var todosRef = new Firebase('your-firebase-app.firebase.io');

    // GET TODOS AS AN ARRAY
    $scope.todos = $firebaseArray(todosRef);
}]);

Define methods

Add Todo

Adding a ToDo item requires creating a unique ID for each item. In this case, we will use the current timestamp generated by JavaScript. 

After generating the timestamp, we use the AngularFire $add() method to add a new item to the firebaseArray with the following attributes: ID, name, and status. The name will be pulled from an input field we will create later in the HTML and the status is defaulted to pending. Finally, we will need to clear the input field.

// ADD TODO ITEM METHOD
$scope.addTodo = function () {

    // CREATE A UNIQUE ID
    var timestamp = new Date().valueOf();

    $scope.todos.$add({
        id: timestamp,
        name: $scope.todoName,
        status: 'pending'
    });

    $scope.todoName = "";

};

Remove ToDo

Once an item is complete, or perhaps once an item was added mistakenly, it needs to be removed from the ToDo list. Removing ToDos is quite simple.

First, we will create a function that accepts the index of the item to be removed, along with the ToDo object itself. Check that the ToDo object exists in the database by verifying that it has an ID, and then remove it from the database by using the AngularFire $remove() method.

// REMOVE TODO ITEM METHOD
$scope.removeTodo = function (index, todo) {

    // CHECK THAT ITEM IS VALID
    if (todo.id === undefined)return;

    // FIREBASE: REMOVE ITEM FROM LIST
    $scope.todos.$remove(todo);

};

Update status

Whenever a task is in progress or completed, it should be displayed on the ToDo List. This is where the statuses come in.

The initial steps of updating a status are identical to removing an item. Create a function that accepts both the index of the item to be removed and the ToDo object and then check that the Object exists by verifying the ID.

The only difference is that we will update the status of the ToDo and use the AngularFire $save() method to update the item in the database.

// MARK TODO AS IN PROGRESS METHOD
$scope.startTodo = function (index, todo) {

    // CHECK THAT ITEM IS VALID
    if (todo.id === undefined)return;

    // UPDATE STATUS TO IN PROGRESS AND SAVE
    todo.status = 'in progress';
    $scope.todos.$save(todo);

};

// MARK TODO AS COMPLETE METHOD
$scope.completeTodo = function (index, todo) {

    // CHECK THAT ITEM IS VALID
    if (todo.id === undefined)return;

    // UPDATE STATUS TO COMPLETE AND SAVE
    todo.status = 'complete';
    $scope.todos.$save(todo);
};

Markup

Building the page is similar to any Angular app. Define the controller and app in the parent div and call our defined methods as needed. Below is the HTML I created for this particular example.

Notice that the input's ng-model is todoName, which we use to define the name of the particular ToDo in the addTodo() method. I also added a simple script using ng-keyup to only allow addTodo() to run if the input is greater than three characters.

Final result

The final result is a simple ToDo list tracker with status updates. While this is all well and good, it's not particularly exciting on its own. The real magic happen when the app is open between two windows.

Any updates made in one instance are immediately pushed to the other instance. This allows people to share todo lists between one another. The application could even be extended by allowing users to create accounts and make their lists private using Firebase's built in authentication.

If you would like to experiment with the example locally, I have provided the example on GitHub.

Where to go from here

Firebase doesn't just have AngularJS support built in with AngularFire. There's also EmberFire, ReactFire, BackboneFire and more, to help you get your application out and running faster no matter what framework you use. Firebase can even be implemented into mobile applications. Check out some more examples the Firebase team built over on their site.

This post is just scratching the surface of Firebase's capabilities. It can help simplify security and manage data efficiently. It's easy to see how implementing Firebase at any stage of development can help make the process much smoother.

If you have any questions or comments, drop me a line. I'd love to hear from you.

Learn more about our Software Development service offering.

Cat Buckley
Cat Buckley
Front End Developer
Contact Cat

Related Articles