You're viewing the legacy docs. They are deprecated as of May 18, 2016.
These docs are for version 2.4.2 and below of the Javascript SDK. Go to our current docs, or see our Web migration guide.

Version 1.2.0Changelog

Using Ionic with Firebase

Ionic is a front-end SDK for developing hybrid mobile apps with HTML5. Because Ionic uses Angular, developers can use AngularFire to easily wire up Firebase with an Ionic app.

Creating a New Ionic App

This guide assumes you are familiar with the basics of Ionic. If you're new to Ionic, check out the Ionic getting started page or their comprehensive guide. Here we'll use the Ionic CLI, a command line utility provided by Ionic. To install it, we'll run the command:

$ npm install -g ionic

For Mac users developing on iOS

iOS apps can only be run on a Mac. If you're developing on a Mac and want to run your app on iOS, you'll need to install XCode from the Mac App Store and then ios-sim from npm using the following command:

$ npm install -g ios-sim

Once we've installed the CLI, we can generate a blank Ionic application template by running:

$ ionic start myapp blank

All of the code we'll be writing will be within the www/ directory. To tell Ionic that we want to enable the app for iOS and Android, we'll run the commands:

$ ionic platform add ios
$ ionic platform add android

More details on setting up different platforms can be found in the Ionic documentation.

Looking for help with Ionic authentication? Skip to the auth section.

Integrating Firebase

We'll include the Firebase and AngularFire libraries as dependencies in our index.html file, right before our app.js include.

<!-- Firebase -->
<script src="https://cdn.firebase.com/js/client/2.2.4/firebase.js"></script>

<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/1.2.0/angularfire.min.js"></script>

Then, in our app.js file we need to add firebase as a dependency in our application module:

angular.module("starter", ["ionic", "firebase"])

Now we're ready to store and sync data with AngularFire using $firebaseArray, $firebaseObject, and $firebaseAuth.

Adding a List View

Let's build a simple grocery list app. We manage the grocery list and connect the Firebase database into the app inside of the ListCtrl controller. The controller code can be found inside app.js.

The <ion-header-bar> is a directive provided by Ionic. It creates a mobile-friendly navigation menu. For now, it just contains a button for adding groceries to the list, which will invoke the addItem() method inside ListCtrl. The css class ion-plus will create a plus sign button using Ionic's Ionicon library.

<body ng-app="starter" ng-controller="ListCtrl">
    <ion-header-bar class="top">
      <h1 class="title">Items</h1>
      <button class="button button-icon ion-plus" ng-click="addItem()">
      </button>
    </ion-header-bar>
</body>

Ionic provides some handy tools for dealing with lists: <ion-list> and <ion-item>. We'll nest those inside an <ion-content> directive to indicate that this is the main body of the view. These may look familiar if you're familiar with table cells or list items in mobile.

<ion-content>
  <ion-list>
    <ion-item ng-repeat="item in items">
      {{item.name}}
    </ion-item>
  </ion-list>
</ion-content>

Now that we have a UI for adding items to our list, we'll write a function to save our list items to our database using the $firebaseArray service.

Saving Data

To save data, we'll create an Items factory that uses $firebaseArray, a service provided by the AngularFire library to synchronize our local Angular array with our remote data:

.factory("Items", function($firebaseArray) {
  var itemsRef = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/items");
  return $firebaseArray(itemsRef);
})

Now we can create our ListCtrl and inject our Items factory as a dependency:

.controller("ListCtrl", function($scope, Items) {

  $scope.items = Items;

  $scope.addItem = function() {
    var name = prompt("What do you need to buy?");
    if (name) {
      $scope.items.$add({
        "name": name
      });
    }
  };
});

This shows the user a prompt to add a new grocery item, and then we use AngularFire's $add function to add the item to our synchronized array. Now when we add items, they'll be stored under a unique ID generated in the database.

Running in the Emulator

This section explains how to run your app in the iOS and Android emulators.

iOS

If you have XCode installed, you can run your app in the iOS emulator by executing the commands:

$ ionic build ios
$ ionic emulate ios
Debugging in the iOS Emulator

You need to open Safari to enable debugging in the iOS emulator. Enable the Develop menu by navigating to the Advanced tab in Safari preferences. Then, once your app is open in the emulator, open a Safari window, click on the Develop menu, then click iOS Simulator and find your app.

Android

If you have Android Studio installed you can run the following commands to open the Android simulator:

$ ionic build android
$ ionic emulate android

Ionic recommends using a tool called Genymotion to emulate an Android environment. You can find more details on this in Ionic's documentation.

User Authentication

Authenticating users is a common feature in many apps. In this example, we'll add Facebook authentication to our Ionic app. Follow the instructions here for registering your app with Facebook and adding your app's ID and Secret to your App Dashboard.

We'll use ng-show and ng-hide to add a login button to our app that will show the user's name when they're authenticated:

<div ng-hide="authData" class="card" ng-click="login()">
  <button class="item">
  Log In with Facebook
  </button>
</div>

<div class="card" ng-show="authData">
  <div class="item item-text-wrap">
    Hello {{authData.facebook.displayName}}!
  </div>
</div>

Angular services are reusable and reduce coupling in the controller. So let's create an Auth factory in app.js that initializes the $firebaseAuth service and pass this into our ListCtrl:

.factory("Auth", function($firebaseAuth) {
  var usersRef = new Firebase("https//<YOUR-FIREBASE-APP>.firebaseio.com/users");
  return $firebaseAuth(usersRef);
})

Now we can use any of AngularFire's authentication methods to log users in with Facebook in our ListCtrl. Mobile browsers often don't support popups, so we'll use a redirect here. It's important to keep in mind that emulators treat redirects differently, which we'll explain below.

$scope.login = function() {
  Auth.$authWithOAuthRedirect("facebook");
};

If the authentication redirect is successful, the user will be routed to a login page on Facebook's domain. So the only thing we need to handle from the promise is the catch() block, which may be called if an error occurs.

Authentication in the Emulator

When we run our app in the iOS or Android emulator, we get a TRANSPORT_UNAVAILABLE error logged to the console. Because the emulator might not support redirects, we need to authenticate with a popup if we get this error. To do this, we'll need to handle this specific error in our catch() block:

$scope.login = function() {
    Auth.$authWithOAuthRedirect("facebook").then(function(authData) {
      // User successfully logged in
    }).catch(function(error) {
      if (error.code === "TRANSPORT_UNAVAILABLE") {
        Auth.$authWithOAuthPopup("facebook").then(function(authData) {
          // User successfully logged in. We can log to the console
          // since we’re using a popup here
          console.log(authData);
        });
      } else {
        // Another error occurred
        console.log(error);
      }
    });
};

After authentication completes, we'll be loading a new page. We can capture the authentication state by listening to the $onAuth() function for authentication events. This method is called each time authentication state changes. The authData will be null when logged out and an object when authenticated:

Auth.$onAuth(function(authData) {
  if (authData === null) {
    console.log("Not logged in yet");
  } else {
    console.log("Logged in as", authData.uid);
  }
  $scope.authData = authData; // This will display the user's name in our view
});
Configuring other OAuth providers

In addition to Facebook, other OAuth providers and email / password authentication are set up in a very similar way. Details on our other supported providers can be found here.

Installing InAppBrowser

Our app works in the browser, but because there is no concept of redirects on mobile we need to add Cordova InAppBrowser as a dependency to make sure authentication works on iOS and Android:

$ cordova plugins add org.apache.cordova.inappbrowser

By default Cordova will whitelist every domain, but it's best practice to only whitelist the domains we're using in our application. To do this, we'll install cordova-plugin-whitelist. Then we'll add the database and authentication servers' domains to our config.xml file using an <allow-intent> tag:

<allow-intent href="*.firebaseio.com" />
<allow-intent href="auth.firebase.com" />

For details on configuring other whitelist domains in your application, check out the documentation on whitelisting domains.

We can now successfully log users in! We have a hybrid mobile app that works on iOS and Android written entirely in JavaScript. If you're looking for more Firebase + Ionic resources, check out our getting started screencast. For Ionic specific questions, check out their community forum.