How to Show Different Native Modal Windows In Ionic Framework

Written by on August 25, 2015

How to Show Different Native Modal Windows In Ionic Framework

ngCordova provides several types of the modal window, of course depending on a smart device environment. I will try to show you every single one of them.

Note: If this tutorial was helpful, you need further clarification, something is not working or you have a request for another Ionic post? Furthermore, leave me a comment below if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com. Thanks and have a nice day!

Preparation

Before we can do anything make sure you have the following:

  • Android Environment (or iOS if your working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova

If you don’t have a preset Ionic + Android environment, find more information here: Ionic Framework | Installation Guide.

1. Update Ionic & Cordova

First thing first, you should update nodeJS to the latest version. Without nodeJS, we wouldn’t be able to update correctly to the latest Ionic and Cordova.

Next, update Ionic and Cordova, older versions may not work with this tutorial:

npm update -g cordova ionic

2. Create a New Project

ionic start IonicModalsDemo blank
cd IonicModalsDemo
Warning: Since some of you never worked with Ionic CLI. From this point and further, every time I tell you to execute something, do that inside a project folder.

Because we’re working with Android, we need to add necessary files it to our project:

ionic platform add android

For MacOS users, do it like this:

ionic platform add ios

3. Download ngCordova archive

ngCordova is a collection of 63+ AngularJS extensions on top of the Cordova API that make it easy to build, test, and deploy Cordova mobile apps with AngularJS. While we can make this work without ngCordova, it’s much more practical this way. This collection also holds many Ionic Framework compatible plugins.

Download ngCordova zip file, here’s site link:

Official Site
Docs
Download Link

Unzip this archive, find a file name called: ng-cordova.min.js, it should be available at this location: ng-cordova-master\dist\.

Open your newly created project directory and copy ng-cordova.min.js to this location: IonicModalsDemo\www\js.

Now include this location to index.html located at IonicModalsDemo\www; add it above cordova.js file, like this:

<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>

4. Include Cordova Plugins

Add required plugin:

cordova plugin add https://github.com/EddyVerbruggen/cordova-plugin-actionsheet.git
cordova plugin add org.apache.cordova.dialogs
cordova plugin add https://github.com/Paldom/PinDialog.git
cordova plugin add https://github.com/Paldom/SpinnerDialog.git
cordova plugin add https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin.git
cordova plugin add cordova-plugin-whitelist

Install Whitelist plugin only if you’re using Cordova 4.0 +. Without it you’ll receive “Application Error: There was a network error.” error.

One note, some of these plugins may not work with Cordova 5.1.1, it’s an internal Cordova error. So use any other Cordova version. If you already have version 5.1.1, do this:

npm uninstall -g cordova
npm install -g cordova@5.0.0

Development

At this point, you should have everything set up and ready, we can start working on our example.

Go to IonicModalsDemo project directory and find app.js, alter angular.module line and include ngCordova service, like this:

var app = angular.module('starter', ['ionic', 'ngCordova'])

Open index.html file, add a controller to ion-content directive:

  <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title"Modals Example</h1>
      </ion-header-bar>
      <ion-content ng-controller="ModalsController">

      </ion-content>
   </ion-pane>

Initialize this controller in app.js file; don’t forget to inject these services:

app.controller('ModalsController', function($scope, $cordovaActionSheet, $cordovaDialogs, $cordovaPinDialog, $cordovaSpinnerDialog, $cordovaToast) {

});

If you’re using Cordova 4+, you will need to check if there’s a Whitelist plugin installed with your project. If you have it, add this security meta tag to your index.html HEAD content:

<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">

Without it your application will throw an error during the app initialization, after that it will continually throwing no security meta-tag found. While not a blocking point, constant console log warnings will make it hard to do any debugging.

Show an Action Sheet:

$scope.showActionSheet = function() {
	var options = {
		title: 'What do you want with this image?',
		buttonLabels: ['Share via Facebook', 'Share via Twitter'],
		addCancelButtonWithLabel: 'Cancel',
		androidEnableCancelButton : true,
		winphoneEnableCancelButton : true,
		addDestructiveButtonWithLabel : 'Delete it'
	};

	$cordovaActionSheet.show(options)
		.then(function(btnIndex) {
			var index = btnIndex;
	});
};

Show a dialog:

$scope.showDialog = function() {		
	$cordovaDialogs.confirm('Do you like cats?', 'Question', ['Yes','No'])
		.then(function(buttonIndex) {
		  // no button = 0, 'OK' = 1, 'Cancel' = 2
		  var btnIndex = buttonIndex;
		  console.log(btnIndex);
		});
};

Show a pin dialog:

$scope.showPinDialog = function() {		
	$cordovaPinDialog.prompt('Some message here').then(
		function(result) {
			console.log('Entered value : ' + result.input1);
		},
		function (error) {
			console.log('Error');
	});
};		

Show a spinner dialog:

$scope.showSpinnerDialog = function() {		
	$cordovaSpinnerDialog.show("Warning","Self destruct imminent!", true);
	
	setTimeout(function(){ 
		$cordovaSpinnerDialog.hide();
	}, 3000);
};		

Show a toast:

$scope.showToast = function() {		
	$cordovaToast
		.show("Here's a message", 'short', 'center')
		.then(function(success) {
			console.log('Success');
		}, function (error) {
			console.log('Error');
		});
};			

Example

This is what our application looks like:

HTML

Application main page.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>
 
    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
 
    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>
 
    <!-- cordova script (this will be a 404 during development) -->
    <script src="js/ng-cordova.min.js"></script>    
    <script src="cordova.js"></script>
 
    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body ng-app="starter">
 
    <ion-pane>
        <ion-header-bar class="bar-stable">
            <h1 class="title">Modal examples</h1>
        </ion-header-bar>
        <ion-content ng-controller="ModalsController">
			<button class="button button-full button-positive" ng-click="showActionSheet()">
			  Open the Action Sheet
			</button>
            <button class="button button-full button-positive" ng-click="showDialog()">
			  Open the Dialog
			</button>
			<button class="button button-full button-positive" ng-click="showPinDialog()">
			  Open the Pin Dialog
			</button>
			<button class="button button-full button-positive" ng-click="showSpinnerDialog()">
			  Open the Spinner Dialog
			</button>
			<button class="button button-full button-positive" ng-click="showToast()">
			  Open the Toast
			</button>
        </ion-content>
    </ion-pane>
	
  </body>
</html>

JavaScript

Application JavaScript file.

// Ionic Starter App
 
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var app = angular.module('starter', ['ionic','ngCordova']);
 
app.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if(window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        }
        if(window.StatusBar) {
            StatusBar.styleDefault();
        }
    });
});

app.controller('ModalsController', function($scope, $cordovaActionSheet, $cordovaDialogs, $cordovaPinDialog, $cordovaSpinnerDialog, $cordovaToast) {
	
	document.addEventListener("deviceready", function () {

		$scope.showActionSheet = function() {
			var options = {
				title: 'What do you want with this image?',
				buttonLabels: ['Share via Facebook', 'Share via Twitter'],
				addCancelButtonWithLabel: 'Cancel',
				androidEnableCancelButton : true,
				winphoneEnableCancelButton : true,
				addDestructiveButtonWithLabel : 'Delete it'
			};

			$cordovaActionSheet.show(options)
				.then(function(btnIndex) {
					var index = btnIndex;
			});
		};
		
		$scope.showDialog = function() {		
		    $cordovaDialogs.confirm('Do you like cats?', 'Question', ['Yes','No'])
				.then(function(buttonIndex) {
				  // no button = 0, 'OK' = 1, 'Cancel' = 2
				  var btnIndex = buttonIndex;
				  console.log(btnIndex);
				});
		};
		
		$scope.showPinDialog = function() {		
		    $cordovaPinDialog.prompt('Some message here').then(
				function(result) {
					console.log('Entered value : ' + result.input1);
				},
				function (error) {
					console.log('Error');
		    });
		};		
		
		$scope.showSpinnerDialog = function() {		
			$cordovaSpinnerDialog.show("Warning","Self destruct imminent!", true);
			
			setTimeout(function(){ 
				$cordovaSpinnerDialog.hide();
			}, 3000);
		};
		
		$scope.showToast = function() {		
			$cordovaToast
				.show("Here's a message", 'short', 'center')
				.then(function(success) {
					console.log('Success');
				}, function (error) {
					console.log('Error');
				});
		};		
		
	}, false);	
	
});

Deployment

Next step, we need to build our application:

ionic build android

Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.

When this step ends, look at the output log, last two lines should look something like this:

Built the following apk(s):
    D:\Development\IonicModalsDemo\platforms\android\build\outputs\apk\android-debug.apk

We’ll use the last line location to deploy our application. Make sure your smartphone is prepared to accept an incoming application. In case of Android platform, you must enable Developer Options and USB Debugging.

Do this:

adb install -r platforms\android\build\outputs\apk\android-debug.apk

or you can do this:

ionic run android -l -c -s
Categories

2 thoughts on “How to Show Different Native Modal Windows In Ionic Framework”

  1. Hi, nice article. I’ve a question, is this application must run on a simulator ? because when I tried to run on my browser, I got error Cannot read property ‘spinnerDialog’ of undefined.

Leave a Reply