Taking Your Cordova App Further with Onsen UI

Share this article

In the first part of this tutorial, we looked at how to get started with mobile app development using Onsen UI, designing the user sign in and sign up pages. In this tutorial, we’ll make these pages functional. We’ll be utilizing Firebase as a backend for the app. In Onsen UI we can use both jQuery and AngularJS for development. In this tutorial we’ll be using AngularJS.

Source code from this tutorial is available on GitHub.

Getting started

Download or clone the first tutorials source code. Install all the required dependencies as shown:

git clone https://github.com/sitepoint-examples/OnsenUI--Part1
cd OnsenUI--Part1
npm install
npm install -g gulp
gulp serve

Point your browser to http://localhost:8901/index.html and you should see the app we designed in first tutorial. You can also use the android emulator to run the app as we did in the first tutorial.

Implementing Sign In

Let’s start by defining a controller for our app. If you open up /OnsenUI--Part1/www/js/app.js you should see a controller already defined.

(function() {
    'use strict';
    var module = angular.module('app', ['onsen']);

    module.controller('AppController', function($scope) {
      // more to come here
    });

})();

First we’ll validate the username and password for empty values. If there are any issues with validation, we’ll show a modal window with a validation message. Otherwise we’ll authenticate against a Firebase database.

Let’s define a method called SignIn inside the controller AppController as shown below:

$scope.data = [];

$scope.SignIn = function() {
    var user = $scope.data.username;
    var pass = $scope.data.password;
    if (user && pass) {
        // success logic
    } else {
        // failure logic
    }
};

Add the ngModel directive to the username and password input text boxes in index.html as shown below:

<input ng-model="data.username" type="text" placeholder="Username" class="text-input text-input--transparent" style="margin-top:8px; width: 100%;" />
<input ng-model="data.password" type="password" placeholder="Password" class="text-input text-input--transparent" style="margin-top:8px; width: 100%;" />

Next, we’ll use the ons-modal component of Onsen UI to show a validation pop up. Add the following html code to the sign in ons-page (Should be around line 92).

<ons-modal var="modal">
    <br>
    <br>Invalid Username or Password.
    <br>
</ons-modal>

Now add the modal show code to the failure logic of SignIn, replacing the // failure logic comment:

modal.show();

Add the modal hide code to the ng-click event of the HTML we just added as shown below:

<ons-modal var="modal" ng-click="modal.hide()">
    <br>
    <br>Invalid Username or Password.
    <br>
</ons-modal>

Add the ngClick directive to the Sign in button as shown below:

<ons-button id="btnSignIn" modifier="large" ng-click="SignIn()">
    SignIn
</ons-button>

Start the server and click on the sign in button with an empty username or password. The modal validation message will appear. Click anywhere on the pop up and it will disappear.

Here is a demo of the above code in action.

Now, let’s validate the username and password against Firebase. To get started with Firebase, you’ll need to register for a free account. Once registered and logged in, you’ll get a firebase url which in my case is :

https://burning-fire-1723.firebaseio.com/

Include the following scripts in index.html:

<script type='text/javascript' src='https://cdn.firebase.com/js/client/1.0.17/firebase.js'></script>
<script type='text/javascript' src='https://cdn.firebase.com/js/simple-login/1.6.1/firebase-simple-login.js'></script>

Firstly we need to create an instance of firebase using our firebase url. Then using this firebase instance, create a FirebaseSimpleLogin instance. Place the this code after the module.controller definition in app.js:

var firebaseRef = new Firebase('https://burning-fire-1723.firebaseio.com');

var auth = new FirebaseSimpleLogin(firebaseRef, function(error, user) {
    if (!error) {
        if (user) {
            // On success authentication
            console.log(user);
        }
    }
});

Inside the SignIn function we’ll authenticate the username and password as shown, replace the current function with the code below:

$scope.SignIn = function() {
    var user = $scope.data.username;
    var pass = $scope.data.password;
    if (user && pass) {
        // success logic
        auth.login('password', {
            email: user,
            password: pass
        });
    } else {
        // failure logic
        modal.show();
    }
};

We have used auth.login to authenticate the username and password against the firebase database. On a successful authentication the user will be logged in.

In order to enable the authentication process, firstly log into firebase and open the application you are currently working on. From the left side menu, click on Login & Auth. Under the Email & Password tab, check the Enable Email & Password Authentication.

Add a new user to the firebase database with a username and password. Now, run the app and try log in using the new username and password. Check the browser console which will have the user logged on successful user authentication.

Here is a demo of the above code in action. Try to sign in using username sam@sam.com and password sam.

Next on a successful user sign in, we’ll redirect the user to home.html. Create a new file called home.html with the following code.

<ons-template id="home.html">
    <ons-page>
        <ons-toolbar>

            <div class="center">Welcome</div>
            <div class="right">

                <ons-icon icon="ion-log-out" size="40px" title="Logout" style="cursor:pointer;" ng-click="logout()"></ons-icon>

            </div>
        </ons-toolbar>

        <div style="text-align: center">
            <br />
            <ons-page>

                <p style="padding-top: 100px; color: #999; text-align: center">Welcome Home {{username}}!!</p>

            </ons-page>
        </div>
    </ons-page>
</ons-template>

Add a new method called logout as shown:

$scope.logout = function() {
    auth.logout();         // logging out the firebase
    $scope.data = [];      // clearing user data
    myNavigator.popPage(); // redirecting to sign in page
};

Now modify the FirebaseSimpleLogin callback as shown:

var auth = new FirebaseSimpleLogin(firebaseRef, function(error, user) {
    if (!error) {
        if (user) {
            $scope.username = user.email;
            myNavigator.pushPage('home.html', {
                animation: 'slide'
            });
        }
    }
});

We have used ons-navigator for page navigation. myNavigator.pushPage is used to navigate to home.html page.

Here is a demo of the above code in action.

Implementing Sign Up

We’ll be implementing sign up functionality also using firebase. In the sign up page we currently have three input fields for sign up. We’ll be using only email and password since that’s all that’s required for firebase user sign up.

Firstly add the ngModel directive to both the fields as shown:

<ons-list-item>
    <input type="text" placeholder="Email Address" ng-model="reg.email" class="text-input text-input--transparent" style="margin-top:58px; width: 100%;">
</ons-list-item>

<ons-list-item>
    <input type="text" ng-model="reg.pass" placeholder="Password" class="text-input text-input--transparent" style="margin-top:8px; width: 100%;">
</ons-list-item>

Create a SignUp method in AppController which will validate the email and password for empty values. Use the auth.create method to sign up a new user as below:

$scope.reg = [];
$scope.SignUp = function() {
    var email = $scope.reg.email;
    var password = $scope.reg.pass;
    auth.createUser(email, password, function(error, user) {
        if (!error) {
            myNavigator.popPage();
        } else {
            alert('error');
        }
    });
};

Add the ngClick directive to the Sign Up button as below:

<ons-button modifier="large" ng-click="SignUp()">
    Sign Up
</ons-button>

Add a new modal to the Sign Up page which we’ll show incase the user doesn’t enter an email or password. Here is how it looks:

<ons-modal ng-click="modal.hide()" var="modal">
    <br>
    <br>Enter Email Address and Password.
    <br>
</ons-modal>

Modify the SignUp function as shown below:

$scope.SignUp = function() {
    var email = $scope.reg.email;
    var password = $scope.reg.pass;
    if (email && password) {
        auth.createUser(email, password, function(error, user) {
            if (!error) {
                myNavigator.popPage();
            } else {
                alert('error');
            }
        });
    } else {
        modal.show();   // to show validation pop up message
    }
};

Now restart the app and try signing up. On a successful sign up it will navigate to the Sign In page. Try signing in using the new credentials and you should be signed in.

Here is a demo of the above sign in and sign up functionality in action.

Conclusion

In this tutorial, we implemented the sign in and sign up functionality using the Onsen UI framework and Firebase as a back end.

Have a look at the number of other components offered by Onsen UI. For an in depth exploration of the Onsen UI framework, refer the official docs.

Do let us know your thoughts in the comments below!

Frequently Asked Questions (FAQs) about Cordova App with Onsen UI

What is the difference between Cordova and Onsen UI?

Cordova and Onsen UI are both tools used in mobile app development, but they serve different purposes. Cordova, also known as PhoneGap, is a mobile application development framework that allows developers to build applications using HTML, CSS, and JavaScript. On the other hand, Onsen UI is a front-end framework for developing mobile apps. It provides a collection of ready-to-use components that can be used to create a user interface for your app. While Cordova allows you to create a mobile app with web technologies, Onsen UI helps you design the look and feel of your app.

How can I integrate Onsen UI with Cordova?

Integrating Onsen UI with Cordova is a straightforward process. First, you need to install Cordova and create a new project. Once the project is set up, you can add Onsen UI to your project by downloading it from the official website or using npm. After adding Onsen UI, you can start building your app by creating HTML files and using Onsen UI components. You can then use Cordova to build and run your app on a mobile device or emulator.

Can I use Onsen UI without Cordova?

Yes, you can use Onsen UI without Cordova. Onsen UI is a standalone framework that can be used to create mobile apps using HTML, CSS, and JavaScript. However, if you want to access native device features or package your app for distribution on app stores, you will need to use a tool like Cordova or another hybrid mobile app development framework.

What are some common issues when using Cordova with Onsen UI?

Some common issues when using Cordova with Onsen UI include problems with the layout of Onsen UI components, issues with the Cordova plugins, and difficulties in debugging. To resolve these issues, make sure you are using the latest versions of Cordova and Onsen UI, check the documentation for both tools, and use debugging tools like Chrome DevTools.

How can I debug a Cordova app with Onsen UI?

Debugging a Cordova app with Onsen UI can be done using various tools. One of the most popular tools is Chrome DevTools, which allows you to inspect your app’s HTML, CSS, and JavaScript code, monitor network requests, and debug JavaScript. You can also use the console.log function to output debug information to the console. Additionally, Cordova provides a debug command that allows you to run your app in a debug mode.

Can I use other front-end frameworks with Cordova?

Yes, you can use other front-end frameworks with Cordova. Cordova is a platform-agnostic framework, which means it can work with any front-end framework that uses HTML, CSS, and JavaScript. This includes popular frameworks like Angular, React, and Vue.js.

How can I optimize the performance of my Cordova app with Onsen UI?

Optimizing the performance of a Cordova app with Onsen UI involves several strategies. These include minimizing the use of heavy animations, optimizing images, using lazy loading for components, and minimizing the use of JavaScript. Additionally, you should regularly test your app on different devices and use performance profiling tools to identify and fix performance bottlenecks.

Can I use Onsen UI for web development?

Yes, you can use Onsen UI for web development. While Onsen UI is primarily designed for mobile app development, it can also be used to create responsive web apps. However, keep in mind that some features and components of Onsen UI are specifically designed for mobile devices and may not work as expected on a desktop browser.

How can I customize the look and feel of my Cordova app with Onsen UI?

Customizing the look and feel of a Cordova app with Onsen UI can be done using CSS. Onsen UI provides a set of CSS components that you can use to style your app. You can also create your own custom CSS styles and apply them to the Onsen UI components.

What are some best practices when using Cordova with Onsen UI?

Some best practices when using Cordova with Onsen UI include keeping your code clean and organized, using version control, regularly testing your app on different devices, optimizing your app for performance, and following the documentation and guidelines provided by both Cordova and Onsen UI.

Jay is a Software Engineer and Writer. He blogs occasionally at Code Handbook and Tech Illumination.

chriswCordovacross platformonsen uiPhonegap
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form