Ionic and Usergrid

Posted by {"display_name"=>"greg", "login"=>"greg", "email"=>"", "url"=>""} on December 01, 2015 · 2 mins read

Step-by-step instructions to create an Ionic app that logs into Usergrid

Ionic Creator

I used the new Ionic Creator to create a login form, side menu and few additional pages. Then exported with the ionic commands

npm install -g cordova ionic
ionic start [appName] creator:cfe60ef40119

Production Ready Steps

I want to create a production ready app so I'm going to follow some of the steps discussed by Agustin Haller here. If you don't care about this, you can skip this section.

npm install gulp-ng-annotate --save-dev
npm install

Add the following to the gulpfile.js

var ngAnnotate = require('gulp-ng-annotate');
var paths = {
    ng_annotate: ['./www/js/*.js']
gulp.task('ng_annotate', function (done) {
      .on('end', done);
gulp.task('default', ['sass', 'ng_annotate']);
gulp.task('watch', function() {, ['sass']);, ['ng_annotate']);

Add the following to the ionic.project file:

"gulpStartupTasks": [

Change the path to the scripts in index.html:

<script src="dist/app/app.js"></script>
<script src="dist/app/controllers.js"></script>
<script src="dist/app/routes.js"></script>
<script src="dist/app/services.js"></script>
<script src="dist/app/directives.js"></script>

Add Usergrid Library

The Usergrid Javascript library can be installed with npm but as of this writing the npm package is behind the latest release. Here's the command to install the npm package:

npm install usergrid --save-dev

You can alternatively, install from the github repository. I'm downloading this usergrid.min.js to the www/js directory from my downloaded Ionic Creator project.

In the projects index.html file, add a reference to the usergrid library:

<script src="js/usergrid.min.js"></script>

Create Usergrid Service

Edit the js/service.js file provided by the Ionic Creator sample and change the BlankFactory to look something like this:

.factory('usergridFactory', [function(){
    var client = new Usergrid.Client({
      URI: '',

    var localFunctions = {
      login: function (username, password) {
        client.login(username, password, function (err) {
          if (err) {
            console.log('login error: ' + error);
          } else {
            console.login('login successful');

    return localFunctions;

Update Login Page

In the login.html file, add the following to the Login button:

ng-click="doLogin(username, password)"

Remove the reference to the route, we'll handle that in the controller:


Update Login Controller

In the controllers.js file, insert the following in the loginCtrl:

$scope.doLogin = function(username, password) {
  usergridFactory.login(username, password)
    .then(function (user) {
    function (errorMsg) { // error
      console.log('Login failed: ' + errorMsg);
      $scope.alerts.push({type: 'danger', msg: errorMsg.message});