Ionic Tutorial
Ionic is open source framework used for developing mobile applications. It provides tools and services for building mobile UI with native look and feel. Ionic framework needs native wrapper to be able to run on mobile devices.
Ionic - Overview
Ionic is front end HTML framework built on top of AngularJS and Cordova. As per official document following is the definition of the Ionic Framework:
Ionic is an HTML5 mobile app development framework targeted at building hybrid mobile apps. Think of Ionic as the front-end UI framework that handles all the look and feel and UI interactions your app needs in order to be compelling. Kind of like "Bootstrap for Native," but with support for a broad range of common native mobile components, slick animations, and beautiful design.
Ionic Framework Features
Following are the most important features of Ionic:
- AngularJSIonic is using AngularJS MVC architecture for building rich single page applications optimized for mobile devices.
- CSS componentsWith native look and feel, these components offer almost all elements that mobile application needs. Components default styling can be easily overridden to accommodate your own design.
- JavaScript componentsThese components are extending CSS components with JavaScript functionalities to cover all mobile elements that can't be done only with HTML and CSS.
- Cordova PluginsApache Cordova plugins offer API needed for using native device functions with JavaScript code.
- Ionic CLIThis is NodeJS utility powered with commands for starting, building, running and emulating Ionic applications.
- Ionic ViewVery useful platform for uploading, sharing and testing your application on native devices.
- LicenceIonic is released under MIT license.
Ionic Framework Advantages
- Ionic is used for hybrid app development. This means that you can package your applications for IOS, Android, Windows Phone and Firefox OS which can save you a lot of working time.
- Starting your app is very easy since Ionic provides useful pre-generated app setup with simple layouts.
- The apps are built in very clean and modular way, so it's very maintainable and easy to update.
- Ionic developers team have very good relationship with google developers team and they are working together to improve the framework. The updates are coming out regularly and Ionic support group is always willing to help when needed.
Ionic Framework Limitations
- Testing can be tricky since browser doesn't always give you right information about the phone enviroment. There is so many different devices and platforms and you usually need to cover most of them.
- It can be hard to combine different native functionalities. Lot of time you will run into plugin compatibility issues, which leads to build errors hard to debug.
- Hybrid apps tend to be slower than the native ones, but since the mobile technologies are improving fast this will not be an issue in the near future.
Ionic - Environment Setup
This chapter will show you how to start with Ionic framework. There are following components needed to start with Ionic:
SN | Software | Description |
---|---|---|
1 | NodeJS | This is the base platform needed to create Mobile Apps using Ionic. You can find detail on NodeJS installation in our NodeJS Environment Setup. Make sure you also install npm while installing NodeJs. |
2 | Android SDK | If you are going to work on Windows platform and developing your apps for Android platform then you should have Android SDK setup on your machine. Here is the detail on Android Environment Setup. |
3 | XCode | If you are going to work on Mac platform and developing your apps for iOS platform then you should have xCode setup on your machine. Here is the detail on iOS Environment Setup. |
4 | Coradova and Ionic | These are the main SDKs which is needed to start working with Ionic. This chapter explains how to setup Ionic in simple step assuming you already have required setup as explained in above steps. |
Installing Cordova and Ionic
We will use windows command prompt for this tutorial. The same steps can be applied to OSX terminal. Open your command window to install Cordova and Ionic:
C:\Users\Username> npm install -g cordova ionic
Creating Apps
While creating your app, you can choose from 3 options to start:
- Tabs App:
- Blank App:
- Side menu app
In your command window open the folder where you want to create your app and try one of the options mentioned below.
Tabs App
If you want to use Ionic tabs template your app will be built with tab menu, header and couple of useful screens and functionalities. This is default Ionic template. Open your command window and choose where you want to create your app.
C:\Users\Username> cd Desktop
This command will change working directory. Our app will be created on Desktop.
C:\Users\Username\Desktop> ionic start myApp tabs
Ionic Start command will create folder named myApp and setup Ionic files and folders.
C:\Users\Username\Desktop> cd myApp
Now we want to access myApp folder that we just created. This is our root folder.
Now let's add Cordova project for android Platform and install basic cordova plugins. This step allows us to run the app on Android emulator or device.
C:\Users\Username\Desktop\myApp> ionic platform add android
Next let's build our app. If you have building errors after running following command you probably didn't install android SDK and its dependencies. Head on to our android tutorial and follow the steps shown there.
C:\Users\Username\Desktop\myApp> ionic build android
The last step of the installation process is to run your app which will start the mobile device if connected or default emulator if there is no device connected. Android default emulator is slow so I suggest you to install Genymotion or some other popular Android emulator.
C:\Users\Username\Desktop\myApp> ionic run android
This will produce below result which is an Ionic Tabs App.
Blank App
If you want to start from scratch you can install Ionic blank template. We will use the same steps we explained above with the addition of ionic start myApp blank instead of ionic start myApp tabs.
C:\Users\Username\Desktop> ionic start myApp blank
Ionic Start command will create folder named myApp and setup Ionic files and folders.
C:\Users\Username\Desktop> cd myApp
Let's add Cordova project for android Platform and install basic cordova plugins as explained above.
C:\Users\Username\Desktop\myApp>ionic platform add android
Next let's build our app:
C:\Users\Username\Desktop\myApp> ionic build android
Finally we will start the App as follows:
C:\Users\Username\Desktop\myApp> ionic run android
This will produce below result which is an Ionic Blank App.
Side Menu App
Third template that you can use is side menu template. The steps are the same as the previous two templates, we will just add sidemenu when starting our app.
C:\Users\Username\Desktop> ionic start myApp sidemenu
Ionic Start command will create folder named myApp and setup Ionic files and folders.
C:\Users\Username\Desktop> cd myApp
Let's add Cordova project for android Platform and install basic cordova plugins as explained above.
C:\Users\Username\Desktop\myApp> ionic platform add android
Next let's build our app:
C:\Users\Username\Desktop\myApp> ionic build android
Finally we will start the App as follows:
C:\Users\Username\Desktop\myApp> ionic run android
This will produce below result which is an Ionic Side Menu App.
Test App in Browser
Since we are working with JavaScript you can serve your app on any web browser. This will speed up your building process but you should always test your app on native emulators and devices. Type the following to serve your app on web browser.
C:\Users\Username\Desktop\myApp> ionic serve
The above command will open your app in web browser. Google chrome provides device mode functionality for mobile development testing. Press F12to access developer console.
The top left corner of the console window click has "Toggle device mode" icon. Next you need to click "Dock to right" icon in top right corner. Refresh the page and you should be ready for testing on web browser.
Project Folder Structure
Ionic creates the following directory structure for all type of apps. This is really important for Ionic developer to understand the purpose of every directory and file mentioned below:
Let's have a quick look into every folders and files available in the above mentioned project folder structure:
- hooksHooks are scripts that can be triggered during build process. They are usualy used for Cordova commands customisation and for building automated processes. We will not use this folder during this tutorial.
- platformsThis is the folder where Android and IOS projects are created. You might encounter some platform specific problems during developement that will require these files but you should leave them intact most of the time.
- pluginsThis folder contains Cordova plugins. When you initially create Ionic app some of the plugins will be installed. We will show you how to install Cordova plugins in some of our next chapters.
- resourcesThis folder is used for adding resources like icon and splash screen to your project.
- scssSince Ionic core is built with Sass this is the folder where your Sass file is located. For simplicity we will not use Sass for this tutorial. Our styling will be done using CSS.
- wwwWww is main working folder for Ionic developers. You will spend most of your time here. Ionic gives us their default folder structure inside 'www' but you can always change it to acommodate your own needs. When you open this folder you will find:
- css folder where you will write your CSS styling.
- img for images.
- js contains apps main configuration file (app.js) and AngularJS components (controllers, services, directives). All of your Javascript code will be inside these folders.
- libs are where your libraries will be placed.
- templates for your HTML files.
- index.html as a starting point to your app.
- Other filesSince this is beginners tutorial, we will just mention some of the other files and their purpose.
- .bowerrc is bower configuration file.
- .editorconfig is editor configuration file.
- .gitignore is used to instruct what part of the app should be ignored when you want to push your app to Git repository.
- bower.json will contain bower components and dependencies if you choose to use bower package manager.
- gulpfile.js is used for creating automated tasks using gulp task manager.
- config.xml is Cordova configuration file.
- package.json contains information about the app, dependencies and plugins that are installed using NPM package manager.
Ionic - Colors
Before we start with actual elements avilable in Ionic framework, let's have a little understanding on how Ionic makes use of colors for different elements.
Ionic framework gives us set of nine predefined color classes. You can use these colors or you can override it with your own styling.
Following list shows default set of 9 colors provided by Ionic. We will use these colors for styling different Ionic elements in our next tutorials. For now you can check all the colors below:
Ionic Color Classes
Class | Description | Result |
---|---|---|
light | To be used for white color | |
stable | To be used for light grey color | |
positive | To be used for blue color | |
calm | To be used for light blue color | |
balanced | To be used for green color | |
energized | To be used for yellow color | |
assertive | To be used for red color | |
royal | To be used for violet color | |
dark | To be used for black color |
Ionic Color Usage
Ionic makes use of different classes for each element. For example a header element will have bar class and a button will have button class. To simplify the usage, we use different colors by prefixing element class in a color name.
For example to create a blue color header we will use a bar-calm as follows:
<div class="bar bar-header bar-calm"> ... </div>
Similarly to create a grey color button we will use button-stable class as follows.
<div class="button button-stable"> ... </div>
You can also use Ionic color class like any other CSS class. We will style two paragraphs below with
balanced
(green) and energized
(yellow) color.<p class="balanced">Paragraph 1...</p> <p class="energized">Paragraph 2...</p>
This will produce following result:
You will see the detail in coming chapters when we will create different elements using different classes.
Customizing Colors with CSS
When you want to change some of the Ionic default colors using CSS, you can do it by editing
lib/css/ionic.css
file. In some cases this approach isn't very productive because every element (header, button, footer...) use its own classes for styling. So if you want to change color of the "light" class to orange, you would need to search through all of the elements that use this class and change it. This is useful when you want to change color of a single element, but not very practical for changing color of all elements because it would use too much time.Customizing colors using SASS
SASS provides easier way to change color for all elements at once. If you want to use SASS open your project in command window and type:
C:\Users\Username\Desktop\tutorialApp> ionic setup sass
This will set up SASS for your project. Now you can change default colors if you open
scss/ionic.app.scss
file and type the following before this line @import "www/lib/ionic/scss/ionic";
. We will change balanced
color to dark blue, and energized
color to orange. Two paragraphs we used above are now dark blue and orange.$balanced: #000066 !default; $energized: #FFA500 !default;
Now if you use following example:
<p class="balanced">Paragraph 1...</p> <p class="energized">Paragraph 2...</p>
This will produce following result:
All of the Ionic elements that are using these classes will change to dark blue and orange. Take into consideration that you don't need to use Ionic default colors classes. You can always style elements the way you want.
Important Note
www/css/style.css
file will be removed from the header of the index.html
after you install SASS. You will need to link it manually if you still want to use it. Open your index.html
and add the following code inside the header
.<link href="css/style.css" rel="stylesheet">
Ionic - Header
Ionic header bar is located on top of the screen. It can contain title, icons, buttons or some other elements on top of it. There are predefined classes of headers that you can use. You can check all of it in this tutorial.
Adding Header
The main class for all the bars you might use in your app is bar. This class will always be applied to all the bars in your app. All bar subclasses will use prefix
bar
.
If you want to create header you need to add bar-header after your main barclass. Open your www/index.html file and add header class inside your bodytag. We are adding header to index.html body because we want it to be available on every screen in the app.
Since bar-header class has default (white) styling applied we will add title on top of it so you can differentiate it from the rest of your screen.
<div class="bar bar-header"> <h1 class="title">Header</h1> </div>
Above code will produce following screen:
Header Colors
If you want to style your header you just need to add appropriate color class to it. When you style your elements you need to add your main element class as prefix to your color class. Since we are styling header bar, the prefix class will be bar and color class that we want to use in this example is positive (blue).
<div class="bar bar-header bar-positive"> <h1 class="title">Header</h1> </div>
Above code will produce following screen:
You can use either of the following nine classes to give a color of your choice to your app header:
Color Class | Description | Result |
---|---|---|
bar-light | To be used for white color | |
bar-stable | To be used for light grey color | |
bar-positive | To be used for blue color | |
bar-calm | To be used for light blue color | |
bar-balanced | To be used for green color | |
bar-energized | To be used for yellow color | |
bar-assertive | To be used for red color | |
bar-royal | To be used for violet color | |
bar-dark | To be used for black color |
Header Elements
We can add other elements inside the header. Following is an example to add menu button and home button inside a header. We will also add icons on top of our header buttons.
<div class="bar bar-header bar-positive"> <button class="button icon ion-navicon"></button> <h1 class="title">Header Buttons</h1> <button class="button icon ion-home"></button> </div>
Above code will produce following screen:
Sub Header
You can create a sub header which will be located just below the header bar. Following example is showing how to add header and sub header to your app. Here we have styled Sub header is with "assertive" (red) color class.
<div class="bar bar-header bar-positive"> <button class="button icon ion-navicon"></button> <h1 class="title">Header Buttons</h1> <button class="button icon ion-home"></button> </div> <div class="bar bar-subheader bar-assertive"> <h2 class="title">Sub Header</h2> </div>
Above code will produce following screen:
When your route is changed to any of the app screens you will notice that header and sub header are covering some of the content as shown below.
To fix this you need to add has-header or has-subheader class to the ion-content tags of your screens. Open one of your HTML files from www/templates and add has-subheader class to ion-content. If you only use header in your app you will need to add has-header class instead.
<ion-content class="padding has-subheader">
Above code will produce following screen:
Ionic - Content
Almost every mobile app contains some fundamental elements. Usualy those elements include header and footer that will cover top and bottom part of the screen. All the other elements will be placed between those two. Ionic provide ion-content element that serves as a containiner that will wrap all the other elements that we want to create.
Ionic - Footer
Ionic footer is placed at the bottom of the app screen. Working with footers is almost the same as working with headers.
Adding Footer
The main class for Ionic footers is bar (the same as header). When you want to add footer to your screens you need to add bar-footer class to your element after the main bar class. Since we want to use our footer on every screen in the app, we will add it to the body of the index.html file. We will also add title for our footer.
<div class="bar bar-footer"> <h1 class="title">Footer</h1> </div>
Above code will produce following screen:
Footer Colors
If you want to style your footer you just need to add appropriate color class to it. When you style your elements you need to add your main element class as prefix to your color class. Since we are styling footer bar, the prefix class will be bar and color class that we want to use in this example is assertive (red).
<div class="bar bar-footer bar-assertive"> <h1 class="title">Footer</h1> </div>
Above code will produce following screen:
You can use either of the following nine classes to give a color of your choice to your app footer:
Color Class | Description | Result |
---|---|---|
bar-light | To be used for white color | |
bar-stable | To be used for light grey color | |
bar-positive | To be used for blue color | |
bar-calm | To be used for light blue color | |
bar-balanced | To be used for green color | |
bar-energized | To be used for yellow color | |
bar-assertive | To be used for red color | |
bar-royal | To be used for violet color | |
bar-dark | To be used for black color |
Footer Elements
Footers can contain elements inside it. Most of the time you will need to add buttons with icons inside a footer.
The first button added will always be in the left corner. The last one will be placed on the right. The buttons in between will be grouped next to the first one on the left side of your footer. In following example you can also notice that we use icon class to add icons on top of the buttons.
<div class="bar bar-footer bar-assertive"> <button class="button icon ion-navicon"></button> <button class="button icon ion-home"></button> <button class="button icon ion-star"></button> <button class="button icon ion-checkmark-round"></button> </div>
Above code will produce following screen:
If you want to move your button to the right you can add pull-right class.
<div class="bar bar-footer bar-assertive"> <button class="button icon ion-navicon pull-right"></button> </div>
Above code will produce following screen:
Ionic - Buttons
There are several types of buttons in Ionic Framework and all of the buttons are subtly animated which enhances user experience when using your app. Main class for all button types is button. This class will always be applied to our buttons, and we will also use it as prefix when working with sub classes.
Block Buttons
Block buttons will always have 100% width of their parent container. They will also have small padding applied. You will use button-block class for adding block buttons. If you want to remove padding but keep full width, you can use button-full class.
Following is the example to show the usage of both classes:
<button class="button button-block"> button-block </button> <button class="button button-full"> button-full </button>
Above code will produce following screen:
Button Size
There are two Ionic classes for changing button size: button-small and button-large. Following is the example to show the usage:
<button class="button button-small"> button-small </button> <button class="button button-large"> button-large </button>
Above code will produce following screen:
Button Colors
If you want to style your button you just need to add appropriate color class to it. When you style your elements you need to add your main element class as prefix to your color class. Since we are styling footer bar, the prefix class will be bar and color class that we want to use in this example is assertive (red).
<button class="button button-assertive"> button-assertive </button>
Above code will produce following screen:
You can use either of the following nine classes to give a color of your choice to your app buttons:
Color Class | Description | Result |
---|---|---|
button-light | To be used for white color | |
button-stable | To be used for light grey color | |
button-positive | To be used for blue color | |
button-calm | To be used for light blue color | |
button-balanced | To be used for green color | |
button-energized | To be used for yellow color | |
button-assertive | To be used for red color | |
button-royal | To be used for violet color | |
button-dark | To be used for black color |
Button Outline
If you want your buttons transparent you can apply button-outline class. Buttons with this class will have outline border and transparent background.
To remove border from button you can use button-clear class. The example below shows how to use these two classes.
<button class="button button-assertive button-outline"> button-outline </button> <button class="button button-assertive button-clear"> button-clear </button>
Above code will produce following screen:
Adding Icons
When you want to add Icons to your buttons, the best way is to use icon class. You can place icon on one side of the button by using icon-left or icon-right. You will usually want to move your icon to one side when you have some text on top of your button as showed below.
<button class="button icon ion-home"> </button> <button class="button icon icon-left ion-home"> Home </button> <button class="button icon icon-right ion-home"> Home </button>
Above code will produce following screen:
Button Bar
If you want to group couple of buttons together you can use button-bar class. The buttons will have equal size by default.
<div class="button-bar"> <a class="button button-positive">1</a> <a class="button button-assertive">2</a> <a class="button button-energized">3</a> <a class="button">4</a> </div>
Above code will produce following screen:
Ionic - Lists
Lists are one of the most popular elements of any web or mobile application. They are usually used for displaying various information. They can be combined with other HTML elements for creating different menus, tabs or just to break the monotony of pure text files. Ionic framework offers different list types to make their usage easy.
Creating Ionic List
Every list is created with two elements. When you want to create basic list your <ul> tag needs to have list class assigned, and your <li> tag will use itemclass. Intersting thing is also that you don't even need to use <ul>, <ol> and <li> tags for your lists. You can use any other elements, but important thing is to add list and item classes appropriately.
<div class="list"> <div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> </div>
Above code will produce following screen:
Inset List
When you need a list to fill your own container, you can add list-inset after your list class. This will add some margin to it and it will adjust list size to your container.
<div class="list list-inset"> <div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> </div>
Above code will produce following screen:
Item Dividers
Dividers are used for organizing some elements into logical groups. Ionic gives us item-divider class for this. Again, like with all the other Ionic elements we just need to add item-divider class after the item class. Item dividers are usefull as a list headers since they have stronger styling then other list items by default.
<div class="list"> <div class="item item-divider">Item Divider 1</div> <div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> <div class="item item-divider">Item Divider 2</div> <div class="item">Item 4</div> <div class="item">Item 5</div> <div class="item">Item 6</div> </div>
Above code will produce following screen:
Adding Icons
We already showed you how to add icons to your buttons. When adding icons to list items you need to choose what side you want to place them. There are item-icon-left and item-icon-right classes for this. You can also combine those two classes if you want to have your Icons on both sides. Finally there is item-note class to add text note to your item.
<div class="list"> <div class="item item-icon-left"> <i class="icon ion-home"></i> Left side Icon </div> <div class="item item-icon-right"> <i class="icon ion-star"></i> Right side Icon </div> <div class="item item-icon-left item-icon-right"> <i class="icon ion-home"></i> <i class="icon ion-star"></i> Both sides Icons </div> <div class="item item-icon-left"> <i class="icon ion-home"></i> <span class="text-note">Text note</span> </div> </div>
Above code will produce following screen:
Adding Avatars and Thumbnails
Avatars and thumbnails are similiar. The main difference is that avatars are smaller then thumbnails. Thumbnails are covering most of the full height of the list item while avatars are medium sized circle images. The classes that are used are item-avatar and item-thumbnail.. You can also chose what side you want to place your avatars and thumbnails as shown in thumbnail code example below.
<div class="list"> <div class="item item-avatar"> <img src="my-image.png"> <h3>Avatar</h3> </div> <div class="item item-thumbnail-left"> <img src="my-image.png"> <h3>Thumbnail</h3> </div> </div>
Above code will produce following screen:
Ionic - Cards
Since mobile devices have smaller screen size, cards are one of the best elements for displaying information that will feel user friendly. In our last tutorial we showed you inset lists. Cards are very similiar to inset lists but they offer some additional shadowing that can influence performance for larger lists.
Adding Cards
Default card can be created by adding card class to your element. Cards are usually formed as lists with item class. Usefull class is item-text-wrap. This will help when you have too much text so you want to wrap it inside your card. First card in example below doesn't have item-text-wrap class assigned and the second one is using it.
<div class="card"> <div class="item"> This is a Ionic card without item-text-wrap class. </div> <div class="item item-text-wrap"> This is a Ionic card with item-text-wrap class. </div> </div>
Above code will produce following screen:
Card Header and Footer
We already showed you how you can use item-divider class for grouping lists. This class can be very usefull when working with cards to create card headers. The same class can be used for footers as follows:
<div class="card list"> <div class="item item-divider"> Card header </div> <div class="item item-text-wrap"> Card text... </div> <div class="item item-divider"> Card Footer </div> </div>
Above code will produce following screen:
Complete Card
You can add any element on top of your card. In following example we will show you how to use full-image class together with item-body to get good looking windowed image inside your card.
<div class="card"> <div class="item item-avatar"> <img src="my-image.png"> <h2>Card Name</h2> </div> <div class="item item-body"> <img class="full-image" src="my-image.png"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eget pharetra tortor. Proin quis eros imperdiet, facilisis nisi in, tincidunt orci. Nam tristique elit massa, quis faucibus augue finibus ac. </div>
Above code will produce following screen:
Ionic - Forms
Ionic forms are mostly used for interaction with users and collecting needed info. This tutorial will cover various text input forms and in our next tutorials we will explain how to use other form elements using Ionic framework.
Using Input Form
The best way to use forms is to use list and item as your main classes. Your app will usually consist more then one form element so it make sence to organize it as a list. In the following example you can notice that item element is label tag.
You can use any other element but label will provide ability to tap on any part of the element to focus your text input. You can set placeholder that will look different then the input text and it will be hidden as soon as you start typing. You can see this in example below.
<div class="list"> <label class="item item-input"> <input type="text" placeholder="Placeholder 1"> </label> <label class="item item-input"> <input type="text" placeholder="Placeholder 2"> </label> </div>
Above code will produce following screen:
Ionic Labels
Ionic offers some other options for your label. You can use input-label class if you want your placeholder to be on the left side when you type text
<div class="list"> <label class="item item-input"> <input type="text" placeholder="Placeholder 1"> </label> <label class="item item-input"> <input type="text" placeholder="Placeholder 2"> </label> </div>
Above code will produce following screen:
Stacked Label
Stacked label is the other option that allows moving your label on top or the bottom of the input. To achieve this we will add item-stacked-label class to our label element and we need to create new element and assign input-labelclass to it.
If we want it to be on top we just need to add this element before input tag. This is shown in our example below. Notice that the span tag is before inputtag. If we changed their places it would appear below it on screen.
<div class="list"> <label class="item item-input item-stacked-label"> <span class="input-label">Label 1</span> <input type="text" placeholder="Placeholder 1"> </label> <label class="item item-input item-stacked-label"> <span class="input-label">Label 2</span> <input type="text" placeholder="Placeholder 2"> </label> </div>
Above code will produce following screen:
Floating Label
Floating labels are third option we can use. These labels will be hidden before we start typing. As soon the typing starts they will appear on top of the element with nice floating animation. We can use floating labels the same way as we used stacked labels. The only difference is that this time we will use item-floating-label class.
<div class="list"> <label class="item item-input item-floating-label"> <span class="input-label"t>Label 1</span> <input type="text" placeholder="Placeholder 1"> </label> <label class="item item-input item-floating-label"> <span class="input-label">Label 2</span> <input type="text" placeholder="Placeholder 2"> </label> </div>
Above code will produce following screen:
Inset inputs
In our last tutorials we showed how to inset Ionic elements. You can also inset an input by adding item-input-inset class to your item and item-input-wrapper to your label. Wrapper will add aditional styling to your label.
If you add some other elements next to your label the label size will adjust to accomodate the new element. You can also add elements inside your label (usually icon).
Example below shows two inset inputs. The first one have button next to the label, and the second one has icon inside. We used placeholder-icon class to make the icon the same color as the placeholder text. Without it the icon would use the color of the label.
<div class="list"> <div class="item item-input-inset"> <label class="item item-input-wrapper"> <input type="text" placeholder="Placeholder 1"> </label> <button class="button">button</button> </div> <div class="item item-input-inset"> <label class="item item-input-wrapper"> <i class="icon ion-edit placeholder-icon"></i> <input type="text" placeholder="Placeholder 2"> </label> </div> </div>
Above code will produce following screen:
Ionic - Toggle
Sometimes there are two options available for users to choose from. The most efficient way to handle this situations are toggle forms. Ionic gives us classes for toggle elements that are animated and easy to implement.
Using Toggle
Toggle can be implemented using two Ionic classes. First we need to create label for the same reason we explained in last tutorial and assign toggle class to it. Inside our label will be created . You will notice two more ionic classes used in the example below. track class will add background styling to our checkbox and color animation when toggle is tapped. handle class is used to add circle button to it.
This example shows two toggle forms. The first one is checked, the second one isn't.
<label class="toggle"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> <br> <label class="toggle"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label>
Above code will produce following screen:
Multiple Toggles
Most of the time when you want to add more then one element of the same kind in Ionic, the best way is to use list items. The class that is used for multiple toggles is item-toggle. The next example showes how to create list with for toggles. First one and the second one are checked.
<ul class="list"> <li class="item item-toggle"> Toggle 1 <label class="toggle"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> <li class="item item-toggle"> Toggle 2 <label class="toggle"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> <li class="item item-toggle"> Toggle 3 <label class="toggle"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> <li class="item item-toggle"> Toggle 4 <label class="toggle"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> </ul>
Above code will produce following screen:
Styling Toggle
All Ionic color classes can be applyed to toggle element. Prefix will be toggle. We will apply this to label element. below example shows all the colors applied.
<ul class="list"> <li class="item item-toggle"> Toggle Light <label class="toggle toggle-light"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> <li class="item item-toggle"> Toggle Stable <label class="toggle toggle-stable"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> <li class="item item-toggle"> Toggle Positiv> <label class="toggle toggle-positive"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> <li class="item item-toggle"> Toggle Calm <label class="toggle toggle-calm"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> <li class="item item-toggle"> Toggle Balanced <label class="toggle toggle-balanced"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> <li class="item item-toggle"> Toggle Energized <label class="toggle toggle-energized"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> <li class="item item-toggle"> Toggle Assertive <label class="toggle toggle-assertive"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> <li class="item item-toggle"> Toggle Royal <label class="toggle toggle-royal"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> <li class="item item-toggle"> Toggle Dark <label class="toggle toggle-dark"> <input type="checkbox"> <div class="track"> <div class="handle"></div> </div> </label> </li> </ul>
Above code will produce following screen:
Ionic - Checkbox
Ionic checkbox is almost the same as toggle. The two are styled differently but are used for the same purposes.
Adding Checkbox
When creating checkbox form you need to add checkbox class name to both label and input elements. Example below shows two simple checkboxes, one is checked and the other is not.
<label class="checkbox"> <input type="checkbox"> </label> <label class="checkbox"> <input type="checkbox"> </label>
Above code will produce following screen:
Multiple Checkboxes
As we already showed, the list will be used for any multiple elements. Now we will use item-checkbox class for each list item.
<ul class="list"> <li class="item item-checkbox"> Checbox 1 <label class="checkbox"> <input type="checkbox"> </label> </li> <li class="item item-checkbox"> Checkbox 2 <label class="checkbox"> <input type="checkbox"> </label> </li> <li class="item item-checkbox"> Checkbox e <label class="checkbox"> <input type="checkbox"> </label> </li> <li class="item item-checkbox"> Checkbox 4 <label class="checkbox"> <input type="checkbox"> </label> </li> </ul>
Above code will produce following screen:
Styling Checkbox
When you want to style checkbox you need to apply any Ionic color class with checkbox prefix. Check example below to see how it looks like. We will use list of checkboxes for this example.
<ul class="list"> <li class="item item-checkbox checkbox-light"> Checbox 1 <label class="checkbox"> <input type="checkbox"> </label> </li> <li class="item item-checkbox checkbox-stable"> Checkbox 2 <label class="checkbox"> <input type="checkbox"> </label> </li> <li class="item item-checkbox checkbox-positive"> Checkbox 3 <label class="checkbox"> <input type="checkbox"> </label> </li> <li class="item item-checkbox checkbox-calm"> Checkbox 4 <label class="checkbox"> <input type="checkbox"> </label> </li> <li class="item item-checkbox checkbox-balanced"> Checkbox 5 <label class="checkbox"> <input type="checkbox"> </label> </li> <li class="item item-checkbox checkbox-energized"> Checkbox 6 <label class="checkbox"> <input type="checkbox"> </label> </li> <li class="item item-checkbox checkbox-assertive"> Checkbox 7 <label class="checkbox"> <input type="checkbox"> </label> </li> <li class="item item-checkbox checkbox-royal"> Checkbox 8 <label class="checkbox"> <input type="checkbox"> </label> </li> <li class="item item-checkbox checkbox-dark"> Checkbox 9 <label class="checkbox"> <input type="checkbox"> </label> </li> </ul>
Above code will produce following screen:
Ionic - Radio Button
Radio buttons are another form elements that we will be covering. The difference between radio buttons from toggle and checkbox forms is that when using former you choose only one radio button from the list. The later allows you to choose more then one.
Adding Radio Buttons
Since there will always be more then one radio button to choose from, the best way is to create list. We did this whenever we wanted multiple elements. The list item class will be item-radio. Again we will use label for this as with all the other forms. Input will have name attribute. This attribute will group all the buttons that you want to use as possible choice. This can be any name you want. item-content class is used to display options clearly. At the end we will use radio-icon class to add checkmark icon that will be used to mark option that user choosed.
In our example below there are four radio buttons, and the second one is chosen.
<div class="list"> <label class="item item-radio"> <input type="radio" name="group1"> <div class="item-content"> Choice 1 </div> <i class="radio-icon ion-checkmark"></i> </label> <label class="item item-radio"> <input type="radio" name="group1"> <div class="item-content"> Choice 2 </div> <i class="radio-icon ion-checkmark"></i> </label> <label class="item item-radio"> <input type="radio" name="group1"> <div class="item-content"> Choice 3 </div> <i class="radio-icon ion-checkmark"></i> </label> <label class="item item-radio"> <input type="radio" name="group1"> <div class="item-content"> Choice 4 </div> <i class="radio-icon ion-checkmark"></i> </label> </div>
Above code will produce following screen:
Multiple Radio Button Groups
Sometimes you want to create more then one group to choose from. This is what the name attribute is for. Next example will group first two and the last two buttons as two option gropups.
We will use item-divider class to separate two groups. Notice that the first group has name attribute equal to group1 and the secon one use group2.
<div class="list"> <div class=" item item-divider"> Group1 </div> <label class="item item-radio"> <input type="radio" name="group1"> <div class="item-content"> Choice 1 </div> <i class="radio-icon ion-checkmark"></i> </label> <label class="item item-radio"> <input type="radio" name="group1"> <div class="item-content"> Choice 2 </div> <i class="radio-icon ion-checkmark"></i> </label> <div class=" item item-divider"> Group2 </div> <label class="item item-radio"> <input type="radio" name="group2"> <div class="item-content"> Choice 3 </div> <i class="radio-icon ion-checkmark"></i> </label> <label class="item item-radio"> <input type="radio" name="group2"> <div class="item-content"> Choice 4 </div> <i class="radio-icon ion-checkmark"></i> </label> </div>
Above code will produce following screen:
Ionic - Range
Ionic range is used to choose and display level of something. It will represent the actual value in corelation to maximal and minimal value. Ionic offer simple way of working with range.
Using Range
Range are used inside item element. The class that is used is range. We will place this class after the item class. This will prepare container where the range will be placed. After creating container we need to add input and assign rangetype to it and name attribute.
<div class = "item range"> <input type = "range" name = "range1"> </div>
Above code will produce following screen −
Adding Icons
Range will usually require icons to display data clearly. We just need to add icons before and after range input to place them on both sides of the range element.
<div class = "item range"> <i class = "icon ion-volume-low"></i> <input type = "range" name = "volume"> <i class = "icon ion-volume-high"></i> </div>
Above code will produce following screen −
Styling Range
Our next example will show you how to style range with Ionic colors. Color classes will use range prefix. We will create list with nine ranges and style it differently.
<div class = "list"> <div class = "item range range-light"> <input type = "range" name = "volume"> </div> <div class = "item range range-stable"> <input type = "range" name = "volume"> </div> <div class = "item range range-positive"> <input type = "range" name = "volume"> </div> <div class = "item range range-calm"> <input type = "range" name = "volume"> </div> <div class = "item range range-balanced"> <input type = "range" name = "volume"> </div> <div class = "item range range-energized"> <input type = "range" name = "volume"> </div> <div class = "item range range-assertive"> <input type = "range" name = "volume"> </div> <div class = "item range range-royal"> <input type = "range" name = "volume"> </div> <div class = "item range range-dark"> <input type = "range" name = "volume"> </div> </div>
Above code will produce following screen −
Ionic - Select
Ionic select will create simple menu with select options to choose from. Select menu will look differently on different platforms since it's styling is handled by the browser.
Using Select
First we will create label and add item-input and item-select classes. The second class will add additional styling to select form, then we will add input-label class inside that will be used to add a name to our select element. We will also add select with option inside. This is regular HTML5 select element. Example below is showing Ionic select with three options.
<label class = "item item-input item-select"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label>
The above code will produce following screen −
Styling Select
The next example will show you how to apply styling to select. We are creating list with nine differently styled select elements using Ionic colors. Since we are using list with items, item will be prefix to color classes.
<div class = "list"> <label class = "item item-input item-select item-light"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-stable"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-positive"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-calm"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-balanced"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-energized"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-assertive"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-royal"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> <label class = "item item-input item-select item-dark"> <div class = "input-label"> Select </div> <select> <option>Option 1</option> <option selected>Option 2</option> <option>Option 3</option> </select> </label> </div>
The above code will produce following screen −
Ionic - Tabs
Ionic tabs are most of the time used for mobile navigation. Styling is optimized for different platforms. This means that on android devices tabs will be placed at the top of the screen, while on IOS it will be at the bottom. There are different ways of creating tabs. During this tutorial we will show you how to achieve it.
Simple Tabs
Simple tabs menu can be created with tabs class. Inside element that is using this class we need to add tab-item elements. Since tabs are usually used for navigation, we will use <a> tags for tab items. The example is showing menu with four tabs.
<div class = "tabs"> <a class = "tab-item"> Tab 1 </a> <a class = "tab-item"> Tab 2 </a> <a class = "tab-item"> Tab 3 </a> </div>
Above code will produce following screen −
Adding Icons
Ionic provides classes for adding icons to tabs. If you want your tabs to only have icons without any text there is tabs-icon-only class that should be added after tabs class. Of course you need to add icons you want to display.
<div class = "tabs tabs-icon-only"> <a class = "tab-item"> <i class = "icon ion-home"></i> </a> <a class = "tab-item"> <i class = "icon ion-star"></i> </a> <a class = "tab-item"> <i class = "icon ion-planet"></i> </a> </div>
Above code will produce following screen −
You can also add icons and text together. tabs-icon-top and tabs-icon-leftare classes that will place icon above or on the left side of respectively. Implementation is the same as the example before, we will just add new class and text that we want to use. Example below shows icons placed above text.
<div class = "tabs tabs-icon-top"> <a class = "tab-item"> <i class = "icon ion-home"></i> Tab 1 </a> <a class = "tab-item"> <i class = "icon ion-star"></i> Tab 2 </a> <a class = "tab-item"> <i class = "icon ion-planet"></i> Tab 3 </a> </div>
Above code will produce following screen −
Stripped Tabs
Striped tabs can be created by adding container around our tabs with tabs-striped class. This class allows usage of tabs-background and tabs-colorprefixes for adding some of The Ionic colors to tabs menu. In our example below we will use tabs-background-positive (blue) class to style background of our menu, and tabs-color-light (white) to style tab icons. Notice the difference between second tab that is active and the other two that aren't.
<div class = "tabs-striped tabs-background-positive tabs-color-light"> <div class = "tabs"> <a class = "tab-item"> <i class = "icon ion-home"></i> </a> <a class = "tab-item active"> <i class = "icon ion-star"></i> </a> <a class = "tab-item"> <i class = "icon ion-planet"></i> </a> </div> </div>
Above code will produce following screen −
Ionic - Grid
Working with the Ionic grid system is straightforward. There are two main classes row for working with rows and col for columns.
You can choose as much as columns or rows you want. All of them will adjust its size to accommodate available space, although you can change this behaviour to suit your needs.
NOTE − All examples in this tutorial will have borders applied to our grid to be able to display it in a way that is easy to understand.
Simple Grid
Example below shows how to use col and row classes. We will create two rows. First row will have five columns, and the second one will have only three. Notice how width of columns is different in first and second row.
<div class = "row"> <div class = "col">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> <div class = "col">col 4</div> <div class = "col">col 5</div> </div> <div class = "row"> <div class = "col">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> </div>
Above code will produce following screen −
Column Sizes
Sometimes you don't want to leave column sizes automatically assigned. If this is the case you can choose col prefix followed by a number that will represent a percentage of the row width. This will apply only to the column with specific size applied. The other columns will adjust to the available space that is left.
In the example below first column will use 50 percent of the full width and the others will adjust accordingly.
<div class = "row"> <div class = "col col-50">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> <div class = "col">col 4</div> <div class = "col">col 5</div> </div> <div class = "row"> <div class = "col col-50">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> </div>
The above code will produce following screen −
Following table shows available percentage options that Ionic grid system provides −
Column Percentage Classnames
Class Name | Percentage Used |
---|---|
col-10 | 10% |
col-20 | 20% |
col-25 | 25% |
col-33 | 33.3333% |
col-50 | 50% |
col-67 | 66.6666% |
col-75 | 75% |
col-80 | 80% |
col-90 | 90% |
Horizontal and Vertical Positioning
The columns can be offset from the left. It works the same as the specific size of the columns. This time prefix will be col-offset and then we will use the same percentage numbers showed in the table above. Following example shows how can we offset second column of both rows by 25 percent.
<div class = "row"> <div class = "col">col 1</div> <div class = "col col-offset-25">col 2</div> <div class = "col">col 3</div> <div class = "col">col 4</div> <div class = "col">col 5</div> </div> <div class = "row"> <div class = "col">col 1</div> <div class = "col col-offset-25">col 2</div> <div class = "col">col 3</div> </div>
Above code will produce following screen −
You can also vertically align columns inside a row. There are three classes that can be used: top, center and bottom class with col prefix. Code belows shows how to place vertically first three columns of both rows.
NOTE − In the example that follows we added .col {height: 120px} to our CSS to show you columns vertical placing.
<div class = "row"> <div class = "col col-top">col 1</div> <div class = "col col-center">col 2</div> <div class = "col col-bottom">col 3</div> <div class = "col">col 4</div> <div class = "col">col 5</div> </div> <div class = "row"> <div class = "col col-top">col 1</div> <div class = "col col-center">col 2</div> <div class = "col col-bottom">col 3</div> </div>
Responsive Grid
Ionic grid can also be used for responsive layout. There are three classes available. responsive-sm class will collapse columns into single row when the viewport is smaller than landscape phone. responsive-md class will be applied when viewport is smaller than portrait tablet. responsive-lg class will be applied when viewport is smaller than landscape tablet.
First image after following example shows how responsive-sm class looks on mobile device and second one shows how the same responsive grid looks differently on Tablet device.
<div class = "row responsive-sm"> <div class = "col col-25">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> <div class = "col">col 4</div> <div class = "col">col 5</div> </div> <div class = "row responsive-sm"> <div class = "col">col 1</div> <div class = "col">col 2</div> <div class = "col">col 3</div> </div>
Mobile Grid View
Tablet Grid View
Ionic - Padding
Ionic offers easy way to add padding to elements. There are couple of classes that can be used and all of them will add 10px between border of element and it's content. The table below displays all available padding classes.
Padding Classes
Class Name | Class Info |
---|---|
padding | Adds padding around every side. |
padding-vertical | Adds padding to the top and bottom. |
padding-horizontal | Adds padding to the left and right. |
padding-top | Adds padding to the top. |
padding-right | Adds padding to the right. |
padding-bottom | Adds padding to the bottom. |
padding-left | Adds padding to the left. |
Using Padding
When you want to apply some padding to your element you just need to assign one of the classes from the table above. Following example shows two block buttons. First one use padding class and the second one doesn't. You will notice that the first button is larger since it has 10px padding applied.
<div class = "button button-block padding">Padding</div> <div class = "button button-block">No padding</div>
Above code will produce following screen −
Ionic - Javascript Action Sheet
Action Sheet is Ionic service that will trigger slide up pane on the bottom of the screen that you can use for various purposes.
Using Action Sheet
In the example that follows we will show you how to use Ionic action sheet. First we will inject $ionicActionSheet service as a dependency to our controller, then we will create $scope.showActionSheet() function, and last we will create button in our HTML template to call the function we created.
Controller Code
.controller('myCtrl', function($scope, $ionicActionSheet) { $scope.triggerActionSheet = function() { // Show the action sheet var showActionSheet = $ionicActionSheet.show({ buttons: [ { text: 'Edit 1' }, { text: 'Edit 2' } ], destructiveText: 'Delete', titleText: 'Action Sheet', cancelText: 'Cancel', cancel: function() { // add cancel code... }, buttonClicked: function(index) { if(index === 0) { // add edit 1 code } if(index === 1) { // add edit 2 code } }, destructiveButtonClicked: function() { // add delete code.. } }); }; })
HTML Code
<button class = "button">Action Sheet Button</button>
Code Explained
When we tap the button it will trigger $ionicActionSheet.show function and Action Sheet will appear. You can create your own functions that will be called when one of the options is taped. cancel function will close the pane but you can add some other behavior that will be called when cancel option is tapped before the pane is closed.
The buttonClicked function is the place where you can write code that will be called when one of the edit options is tapped. We can keep track of multiple buttons by using index parameter. destructiveButtonCLicked is function that will be triggered when delete option is tapped. This option is red by default.
$ionicActionSheet.show() method has some other useful parameters. You can check them all in following table.
Show method options
Properties | Type | Details |
---|---|---|
buttons | object | Creates button object with a text field. |
titleText | string | The title of the action sheet. |
cancelText | string | The text for cancel button. |
destructiveText | string | The text for a destructive button. |
cancel | function | Called when cancel button, backdrop or hardware back button is pressed. |
buttonClicked | function | Called when one of the buttons is tapped. Index is used for keeping track of which button is tapped. Return true will close the action sheet. |
destructiveButtonClicked | function | Called when destructive button is clicked. Return true will close the action sheet. |
cancelOnStateChange | boolean | If true (default) it will cancel the action sheet when navigation state is changed. |
Ionic - Javascript Backdrop
Ionic Backdrop will overlay content of the screen when applied. It will appear below other overlays (popup, loading etc...). There are two methods that can be used for managing backdrop service. $ionicBackdrop.retain() will apply backdrop over the components, and $ionicBackdrop.release() will remove it.
Using Backdrop
Example below shows how to use backdrop. We are adding $ionicBackdrop as a dependency to controller, then creating $scope.showBackdrop() function that will call retain method immediately and after three seconds it will call release method. We are using $timeout for the release method so we need to add it as a controller dependency too.
You will notice how the screen is darker in the image below since the backdrop is applied.
.controller('myCtrl', function($scope, $ionicBackdrop, $timeout) { $scope.showBackdrop = function() { $ionicBackdrop.retain(); $timeout(function() { $ionicBackdrop.release(); }, 3000); }; })
Ionic - Javascript Content
Almost every mobile app contains some fundamental elements. Usualy those elements include header and footer that will cover top and bottom part of the screen. All the other elements will be placed between those two. Ionic provide ion-content element that serves as a container that will wrap all the other elements that we want to create.
Ionic - Javascript Forms
We already went through Ionic CSS form elements in one of our previous tutorials, and now we will work with Ionic JavaScript forms. In this tutorial we will show you JavaScript checkbox, radio buttons and toggle.
Using ion-checkbox
Let's see how to use Ionic JavaScript checkbox. First we need to create ion-checkbox element in HTML file. Inside of it we will assign ng-model attribute that will be connected to the angular $scope. You will notice that we are using dot when defining value of model even though it would work without it. This will allow us to keep the link between child and parent scopes at all times. This is very important to avoid some issues that could happen in the future. After we created the element, we will bind its value using angular expressions.
<ion-checkbox ng-model="checkboxModel.value1">Checkbox 1</ion-checkbox> <ion-checkbox ng-model="checkboxModel.value2">Checkbox 2</ion-checkbox> <p>Checkbox 1 value is: <b>{{checkboxModel.value1}}</b></p> <p>Checkbox 2 value is: <b>{{checkboxModel.value2}}</b></p>
Next we need to assign values to our model inside controller. The values we will use are false since we want to start with unchecked checkboxes.
$scope.checkboxModel = { value1 : false, value2 : false };
Now when we tap checkbox elements it will automatically change their model value to true as showed below.
Using ion-radio
First we will create three ion-radio elements in our HTML and assign ng-model and ng-value to it. After that, we will display chosen value with angular expression. We will start with all three radio elements unchecked so the value will not be assigned to our screen.
<ion-radio ng-model = "radioModel.value" ng-value = "1">Radio 1</ion-radio> <ion-radio ng-model = "radioModel.value" ng-value = "2">Radio 2</ion-radio> <ion-radio ng-model = "radioModel.value" ng-value = "3">Radio 3</ion-radio> <p>Radio value is: <b>{{radioModel.value}}</b></p>
When we tap second checkbox element the value will change accordingly.
Using ion-toggle
You will notice that toggle is similar to checkbox. We will follow the same steps as we did with our checkbox. In HTML file first we will create ion-toggleelements, then assign ng-model value and then bind expression values of to our view.
<ion-toggle ng-model = "toggleModel.value1">Toggle 1</ion-toggle> <ion-toggle ng-model = "toggleModel.value2">Toggle 2</ion-toggle> <ion-toggle ng-model = "toggleModel.value3">Toggle 2</ion-toggle> <p>Toggle value 1 is: <b>{{toggleModel.value1}}</b></p> <p>Toggle value 2 is: <b>{{toggleModel.value2}}</b></p> <p>Toggle value 3 is: <b>{{toggleModel.value3}}</b></p>
Next we will assign values to $scope.toggleModel in our controller. Since toggle use boolean values we will assign true to first element and false to the other two.
$scope.toggleModel = { value1 : true, value2 : false, value3 : false };
Now we will tap on second and third toggle to show you how the values change from false to true.
Ionic - Javascript Events
There are various Ionic events that can be used to add interactivity with users. Following table explains all Ionic events.
Event Name | Event Detail |
---|---|
on-hold | Called when duration of the touch is more than 500ms. |
on-tap | Called when duration of the touch is less than 250ms. |
on-double-tap | Called when there is double tap touch. |
on-touch | Called immediately when touch begins. |
on-release | Called when touch ends. |
on-drag | Called when touch is moved without releasing around the page in any direction. |
on-drag-up | Called when element is dragged up. |
on-drag-right | Called when the element is dragged to the right. |
on-drag-left | Called when the element is dragged to the left. |
on-drag-down | Called when the element is dragged down. |
on-swipe | Called when any dragging has high velocity moving in any direction. |
on-swipe-up | Called when any dragging has high velocity moving up. |
on-swipe-right | Called when any dragging has high velocity moving to the right. |
on-swipe-left | Called when any dragging has high velocity moving to the left. |
on-swipe-down | Called when any dragging has high velocity moving down. |
Using Events
Since all Ionic events can be used the same way we will show you how to use on-touch event and you can just apply the same principles to the other events. First we will create button and assign on-touch event that will call onTouchFunction().
<button on-touch = "onTouchFunction()" class="button">Test</button>
Then we will create that function in our controller scope.
$scope.onTouchFunction = function() { // Do something... }
Now when touch event occurs onTouchFunction() will be called.
Ionic - Javascript Header
This is Ionic directive that will add header bar.
Using JavaScript Header
To create JavaScript header bar we need to apply ion-header-bar directive in HTML file. Since default header is white we will add title so it will be showed on white background. We will add it to our index.html file.
<ion-header-bar> <h1 class="title">Title!</h1> </ion-header-bar>
Styling header
Just like CSS header bar, the JavaScript counterpart can be styled in similar fashion. To apply color we need to add color class with bar prefix, so if we want to use blue header we will add bar-positive class. We can also move title to the side of the screen by adding align-title attribute. The values for this attribute can be center, left or right.
<ion-header-bar align-title="left" class="bar-positive"> <h1 class="title">Title!</h1> </ion-header-bar>
Adding Elements
You will usually want to add some elements to your header. Following example shows how to place button on the left side and icon to the right side of ion-header-bar. You can also add other elements to your header.
<ion-header-bar class="bar-positive"> <div class="buttons"> <button class="button">Button</button> </div> <h1 class="title">Title!</h1> <div class="buttons"> <button class="button icon ion-home"></button> </div> </ion-header-bar>
Adding Sub Header
Sub header is created when bar-subheader class is added to ion-header-bar. We will add bar-assertive class to apply red color to our sub header.
<ion-header-bar class="bar-positive"> <div class="buttons"> <button class="button">Button</button> </div> <h1 class="title">Title!</h1> <div class="buttons"> <button class="button icon ion-home"></button> </div> </ion-header-bar> <ion-header-bar class="bar-subheader bar-assertive"> <h1 class="title">Subheader</h1> </ion-header-bar>
Ionic - Javascript Footer
This directive will add footer bar at the bottom of the screen.
Using Footer
Ionic footer can be added by applying ion-footer-bar class. Working with it is the same as working with header. We can add title and place it left, center or right by using align-title attribute, and with prefix bar we can Ionic colors. Let's create red colored footer with the title in the middle.
<ion-footer-bar align-title="center" class="bar-assertive"> <h1 class="title">Title!</h1> </ion-footer-bar>
Adding Elements
We can add buttons icons or other elements to ion-footer-bar and their styling will be applied. Let's add button and Icon to our footer.
<ion-footer-bar class="bar-assertive"> <div class="buttons"> <button class="button">Button</button> </div> <h1 class="title">Footer</h1> <div class="buttons"> <button class="button icon ion-home"></button> </div> </ion-footer-bar>
Adding Sub Footer
We showed you how to use sub header. The same way can be created sub footer. It will be located above the footer bar. All we need to do is add bar-subfooter class to our ion-footer-bar element. In example that follows we will add sub-footer above the footer bar we previously created.
<ion-footer-bar class="bar-subfooter bar-positive"> <h1 class="title">Sub Footer</h1> </ion-footer-bar> <ion-footer-bar class="bar-assertive"> <div class="buttons"> <button class="button">Button</button> </div> <h1 class="title">Footer</h1> <div class="buttons" ng-click="doSomething()"> <button class="button icon ion-home"></button> </div> </ion-footer-bar>
Ionic - Javascript Keyboard
Keyboard is one of the automated features in Ionic. This means that Ionic can recognize when there is a need to open keyboard.
Using Keyboard
There are some functionalities that developers can adjust when working with Ionic keyboard. When you want to hide some elements while keyboard is open, you can use hide-on-keyboard-open class. To show you how this works we created input and button that needs to be hidden when keyboard is open.
<label class = "item item-input"> <input type = "text" placeholder = "Input 1"> </label> <button class = "button button-block hide-on-keyboard-open"> button </button>
Now when we tap on input field the keyboard will open automatically and button will become hidden.
One nice feature of Ionic is that it will adjust elements on screen so your focused element is always visible when keyboard is open. Image below shows ten Input forms and the last one is blue.
When we tap the blue form, Ionic will adjust our screen so the blue form is always visible.
NOTE
This will work only if the screen is within a directive that has a Scroll View. If you start with one of the Ionic templates you will notice that all templates use ion-content directive as a container to other screen elements so the Scroll View is always applied.
Ionic - Javascript List
We already discussed Ionic CSS list elements. In this tutorial we will show you JavaScript lists. They allow us to use some new features like swipe, drag and remove.
Using List
The directives used for displaying lists and items are ion-list and ion-item as showed below.
<ion-list> <ion-item> Item 1 </ion-item> <ion-item> Item 2 </ion-item> <ion-item> Item 3 </ion-item> </ion-list>
Delete Button
This button can be added by using ion-delete-button directive. You can use any icon class you want. Since we don't always want to show delete buttons because users might accidentally tap it and trigger delete process we can add show-delete attribute to ion-list and connect it with ng-model. In the example below we will use ion-toggle as a model. When toggle is on delete, the buttons will appear on our list items.
<ion-list show-delete = "showDelete1"> <ion-item> <ion-delete-button class = "ion-minus-circled"></ion-delete-button> Item 1 </ion-item> <ion-item> <ion-delete-button class = "ion-minus-circled"></ion-delete-button> Item 2 </ion-item> </ion-list> <ion-toggle ng-model = "showDelete2"> Show Delete 2 </ion-toggle>
Reorder Button
Ionic directive for reorder button is ion-reorder-button. The element we created has on-reorder attribute that will trigger the function from our controller whenever user is dragging this element.
<ion-list show-reorder = "true"> <ion-item ng-repeat = "item in items"> Item {{item.id}} <ion-reorder-button class = "ion-navicon" on-reorder = "moveItem(item, $fromIndex, $toIndex)"></ion-reorder-button> </ion-item> </ion-list>
$scope.items = [ {id: 1}, {id: 2}, {id: 3}, {id: 4} ]; $scope.moveItem = function(item, fromIndex, toIndex) { $scope.items.splice(fromIndex, 1); $scope.items.splice(toIndex, 0, item); };
When we click the icon on the right we can drag element and move it to some other place in the list.
Option Button
Option button is created using ion-option-button directive. These buttons are showed when list item is swiped to the left and we can hide it again by swiping item element to the right. You can see in example below two buttons that are hidden.
<ion-list> <ion-item> Item with two buttons... <ion-option-button class = "button-positive">Button 1</ion-option-button> <ion-option-button class = "button-assertive">Button 2</ion-option-button> </ion-item> </ion-list>
When we swipe item element to the left, the text will be moved left and buttons will appear on the right side.
Other Functions
collection-repeat is updated version of AngularJs ng-repeat directive. It will only render visible elements on the screen and the rest will be updated as you scroll. This is important performance improvement when you are working with large lists. This directive can be combined with item-width and item-heightattributes for further optimization of the list items.
There are some other useful attributes for working with images inside your list. item-render-buffer represents number of items that are loaded after visible items. The higher this value is, the more items will be preloaded. force-refresh-images will fix an issue with source of the images while scrolling. Both of these classes will influence performance in a negative way.
Ionic - Javascript Loading
Ionic loading will disable any interaction with users when showed and enable it again when it is needed.
Using Loading
Loading is triggered inside controller. First we need to inject $ionicLoading in our controller as dependency. After that we need to call $ionicLoading.show() method and loading will appear. For disabling it there is $ionicLoading.hide() method.
Controller
.controller('myCtrl', function($scope, $ionicLoading) { $scope.showLoading = function() { $ionicLoading.show({ template: 'Loading...' }); }; $scope.hideLoading = function(){ $ionicLoading.hide(); }; });
HTML Code
<button class = "button button-block" ng-click = "showLoading()"></button>
When user taps the button, the loading will appear. You will usually want to hide the loading after some time consuming functionalities are finished.
There are some other option parameters that can be used when working with loading. The explanation is shown in the table below.
Loading option parameters
Options | Type | Details |
---|---|---|
templateUrl | string | Used to load HTML template as loading indicator. |
scope | object | Used to pass custom scope to loading. Default is the $rootScope. |
noBackdrop | boolean | Used to hide the backdrop. |
hideOnStateChange | boolean | Used to hide the loading when state is changed. |
delay | number | Used to delay showing the indicator in milliseconds. |
duration | number | Used to hide the indicator after some time in milliseconds. Can be used instead of hide()method. |
Loading Config
Ionic config is used to configure options you want to be used in all of the $ionicLoading services throughout the app. This can be done by using $ionicLoadingConfig. Since constants should be added to main app module, open your app.js file and add your constant after module declaration.
.constant('$ionicLoadingConfig', { template: 'Default Loading Template...' })
Ionic - Javascript Modal
Navigation is one of the core components of every app. Ionic is using AngularJS UI Router for handling navigation.
Using Navigation
Navigation can be configured in app.js file. If you are using one of the Ionic templates you will notice $stateProvider service injected into app config. The most simple way of creating states for the app is showed in the example below. $stateProvider service will scan the url, find the corresponding state and load the file we defined in app.config.
app.js Code
.config(function($stateProvider) { $stateProvider .state('index', { url: '/', templateUrl: 'templates/home.html'}) .state('state1', {url: '/state1', templateUrl: 'templates/state1.html'}) .state('state2', {url: '/state2', templateUrl: 'templates/state2.html',}); });
The state will be loaded into the ion-nav-view element that can should be placed in index.html body.
index.html Code
<ion-nav-view></ion-nav-view>
When we created states in the example above we were using templateUrl so when state is loaded it will search for matching template file. Now we will open templates folder and create new file state1.html that will be loaded when app url is changed to /state1.
state1.html Code
<ion-view> <ion-content> This is State 1 !!! </ion-content> </ion-view>
Creating Navigation Menu
You can add navigation bar to your app in index.html body by adding ion-nav-bar element. Inside navigation bar we will add ion-nav-back-button with icon. This will be used for returning to previous state. The button will appear automatically when state is changed. We will assign goBack() function that will use $ionicHistory service for handling this functionality. So when user leave home state and go to state1, the back button will appear that can be taped if user want to return to home state again.
index.html Code
<ion-nav-bar class = "bar-positive"> <ion-nav-back-button class = "button-clear" ng-click = "goBack()"> <i class = "icon ion-arrow-left-c"></i> Back </ion-nav-back-button> </ion-nav-bar>
Controller Code
.MyCtrl($scope, $ionicHistory) { $scope.goBack = function() { $ionicHistory.goBack(); }; }
Adding Navigation Elements
Buttons can be added to navigation bar using ion-nav-buttos. This element should be placed inside ion-nav-bar or ion-view. We can assign side attribute with four option values. primary and secondary values will place buttons according to platform that is used. Sometimes you want buttons on one side no matter if it's IOS or Android. If that is the case you can use left or rightattributes instead.
We can also add ion-nav-title to navigation bar. All of the code will be placed in index.html body so it can be used everywhere.
<ion-nav-bar class = "bar-positive"> <ion-nav-title> Title </ion-nav-title> <ion-nav-buttons side = "primary"> <button class = "button"> Button 1 </button> </ion-nav-buttons> </ion-nav-bar>
Other Navigation Attributes
Following table shows other functionalities that can be used with Ionic navigation.
Navigation Attributes
Attribute | Options | Detail |
---|---|---|
nav-transition | none, ios, android | Used to set animation that should be applied when transition occurs. |
nav-direction | forward, back, enter, exit, swap | Used to set the direction of the animation when transition occurs. |
hardwareBackButtonClose | boolean | It will enable closing the modal when hardware back button is clicked. Default value is true. |
Caching
Ionic is caching up to ten views to improve performance. It also offers a way to handle caching manually. Since only backward views are cached and forward ones are loading each time users visit them we can easily set to cache forward views by using following code.
$ionicCinfigProvider.views.forwardCache(true);
We can also set how many states should be cached. If we want three views to be cached, we can use the following.
$ionicConfigProvider.views.maxCache(3);
Caching can be disabled inside $stateProvider or by setting attribute to ion-view. Both examples are below.
$stateProvider.state('state1', { cache: false, url : '/state1', templateUrl: 'templates/state1.html' })
<ion-view cache-view = "false"></ion-view>
Delegate for Controlling Navigation Bar
We can control behavior of the navigation bar using $ionicNavBarDelegateservice. This service needs to be injected to our controller.
HTML Code
<ion-nav-bar> <button ng-click = "setNavTitle('title')"> Set title to banana! </button> </ion-nav-bar>
Controller Code
$scope.setNavTitle = function(title) { $ionicNavBarDelegate.title(title); }
The $ionicNavBarDelegate service has other useful methods.
Methods for $ionicNavBarDelegate
Method | Parameter | Type | Detail |
---|---|---|---|
align(parameter) | center, left, right | string | Used to align the title. |
showBackButton(parameter) | show | boolean | Used to show or hide the back button. |
title(parameter) | title | string | Used to show the new title. |
History
You can track history of the previous, current and the forward views by using $ionicHistory service. Following table shows all of the methods of this service.
Methods for $ionicHistory
Method | Parameter | Type | Detail |
---|---|---|---|
viewHistory | / | object | Returns the app view history data. |
currentView() | / | object | Returns the current view. |
title(parameter) | title | string | Returns the ID of the view which is parent of the current view. |
currentTitle(parameter) | val | string | Returns the title of the current view. It can be updated by setting new valvalue. |
backView() | / | string | Returns the last back view. |
backTitle() | / | string | Returns the title of last back view. |
forwardView() | / | object | Returns the last forward view. |
currentStateName() | / | string | Returns the current state name. |
goBack() | backCount | number | Used to set how many views to go back. Number should be negative. If it is positive or zero it will have no effect.. |
clearHistory() | / | / | Used to clear entire view history. |
clearCache() | / | promise | Used to clear all cached views. |
nextViewOptions() | / | object | Sets the options of the next view. You can look the following example for more info. |
The nextViewOptions() method has three options available. disableAnimate is used for disabling animation of the next view change. disableBack will set the back view to null. historyRoot will set the next view as the root view.
$ionicHistory.nextViewOptions({ disableAnimate: true, disableBack: true });
Ionic - Javascript Popover
This is a view that will appear above the regular view.
Using Popover
Popover can be created by using ion-popover-view element. This element should be added to HTML template and $ionicPopover service needs to be injected into controller.
There are three ways of adding popover. fromTemplate method allows using inline template.
Controller Code
.controller('DashCtrl', function($scope, $ionicLoading, $ionicPopover) { // .fromTemplate() method var template = '<ion-popover-view>' + '<ion-header-bar>' + '<h1 class = "title">Popover Title</h1>' + '</ion-header-bar>'+ '<ion-content>' + 'Popover Content!' + '</ion-content>' + '</ion-popover-view>'; $scope.popover = $ionicPopover.fromTemplate(template, { scope: $scope }); $scope.openPopover = function($event) { $scope.popover.show($event); }; $scope.closePopover = function() { $scope.popover.hide(); }; //Cleanup the popover when we're done with it! $scope.$on('$destroy', function() { $scope.popover.remove(); }); // Execute action on hide popover $scope.$on('popover.hidden', function() { // Execute action }); // Execute action on remove popover $scope.$on('popover.removed', function() { // Execute action }); })
The second and the third way of adding popover is to use fromTemplateUrlmethod. The controller code will be the same for both ways except the fromTemplateUrl value. If HTML is added to existing template, the url will be popover.html. If we want to place HTML into templates folder, then the url will change to templates/popover.html. Both examples can be seen below.
Controller Code
.controller('MyCtrl', function($scope, $ionicPopover) { $ionicPopover.fromTemplateUrl('popover.html', { scope: $scope }).then(function(popover) { $scope.popover = popover; }); $scope.openPopover = function($event) { $scope.popover.show($event); }; $scope.closePopover = function() { $scope.popover.hide(); }; //Cleanup the popover when we're done with it! $scope.$on('$destroy', function() { $scope.popover.remove(); }); // Execute action on hide popover $scope.$on('popover.hidden', function() { // Execute action }); // Execute action on remove popover $scope.$on('popover.removed', function() { // Execute action }); })
Now we will add script with template to the HTML file we are using for calling popover function.
HTML code from Existing HTML file
<script id = "popover.html" type = "text/ng-template"> <ion-popover-view> <ion-header-bar> <h1 class = "title">Popover Title</h1> </ion-header-bar> <ion-content> Popover Content! </ion-content> </ion-popover-view> </script>
If we want to create HTML as a separate file, we can create new HTML file in templates folder and use the same code as we used in the example above just without script tags.
The new created HTML file
<ion-popover-view> <ion-header-bar> <h1 class = "title">Popover Title</h1> </ion-header-bar> <ion-content> Popover Content! </ion-content> </ion-popover-view>
The last thing we need is to create button that will be clicked to show popover.
<button class = "button" ng-click = "openPopover($event)">Add Popover</button>
Whatever way we choose from above examples, the output will always be the same.
The following table shows $ionicPopover methods that can be used.
Method | Option | Type | Detail |
---|---|---|---|
initialize(options) | scope, focusFirst, backdropClickToClose, hardwareBackButtonClose | object, boolean, boolean, boolean | scope is used to pass custom scope to popover. Default is the $rootScope. focusFirstInput is used to auto focus the first input of the popover. backdropClickToClose is used to close popover when clicking the backdrop. hardwareBackButtonClose is used to close popover when hardware back button is pressed. |
show($event) | $event | promise | Resolved when popover is finished showing. |
hide() | / | promise | Resolved when popover is finished hiding. |
remove() | / | promise | Resolved when popover is finished removing. |
isShown() | / | boolean | Returns true if popover is shown or false if it isn't. |
Ionic - JavaScript Popup
This service is used for creating popup window on top of the regular view which will be used for interaction with users. There are four types of popups − show, confirm, alert and prompt.
Using Show Popup
This popup is the most complex of all. To trigger popups we need to inject $ionicPopup service to our controller and then just add a method that will trigger the popup we want to use, in this case $ionicPopup.show(). The onTap(e) function can be used for adding e.preventDefault() method that will keep the popup open if there is no change applied to the input. When popup is closed, the promise object will be resolved.
Controller Code
.controller('MyCtrl', function($scope, $ionicPopup) { // When button is clicked, the popup will be shown... $scope.showPopup = function() { $scope.data = {} // Custom popup var myPopup = $ionicPopup.show({ template: '<input type = "text" ng-model = "data.model">', title: 'Title', subTitle: 'Subtitle', scope: $scope, buttons: [ { text: 'Cancel' }, { text: '<b>Save</b>', type: 'button-positive', onTap: function(e) { if (!$scope.data.model) { //don't allow the user to close unless he enters model... e.preventDefault(); } else { return $scope.data.model; } } } ] }); myPopup.then(function(res) { console.log('Tapped!', res); }); }; })
HTML Code
<button class = "button" ng-click = "showPopup()">Add Popup Show</button>
You are probably noticing in above example some options used. The following table will explain all of the options and their use case.
Show Popup Options
Option | Type | Details |
---|---|---|
template | string | Inline HTML template of the popup. |
templateUrl | string | URL of the HTML template. |
title | string | The title of the popup. |
subTitle | string | The subtitle of the popup. |
cssClass | string | The CSS class name of the popup. |
scope | Scope | A scope of the popup. |
buttons | Array[Object] | Buttons that will be placed in footer of the popup. They can use their own properties and methods. text is displayed on top of the button, type is the Ionic class used for the button, onTap is function that will be triggered when the button is tapped. Returning a value will cause the promise to resolve with the given value. |
Using Confirm Popup
Confirm popup is simpler version of Ionic popup. It contains Cancel and OK buttons that users can press to trigger corresponding functionality. It returns the promise object that is resolved when one of the buttons are pressed.
Controller Code
.controller('MyCtrl', function($scope, $ionicPopup) { // When button is clicked, the popup will be shown... $scope.showConfirm = function() { var confirmPopup = $ionicPopup.confirm({ title: 'Title', template: 'Are you sure?' }); confirmPopup.then(function(res) { if(res) { console.log('Sure!'); } else { console.log('Not sure!'); } }); }; })
HTML Code
<button class = "button" ng-click = "showConfirm()">Add Popup Confirm</button>
The following table explains the options that can be used for this popup.
Confirm Popup Options
Option | Type | Details |
---|---|---|
template | string | Inline HTML template of the popup. |
templateUrl | string | URL of the HTML template. |
title | string | The title of the popup. |
subTitle | string | The subtitle of the popup. |
cssClass | string | The CSS class name of the popup. |
cancelText | string | The text for the Cancel button. |
cancelType | string | The Ionic button type of the Cancel button. |
okText | string | The text for the OK button. |
okType | string | The Ionic button type of the OK button. |
Using Alert Popup
Alert is simple popup that is used for displaying alert information to the user. It has only one button that is used to close the popup and resolve the popups promise object.
Controller Code
.controller('MyCtrl', function($scope, $ionicPopup) { $scope.showAlert = function() { var alertPopup = $ionicPopup.alert({ title: 'Title', template: 'Alert message' }); alertPopup.then(function(res) { // Custom functionality.... }); }; })
HTML Code
<button class = "button" ng-click = "showAlert()">Add Popup Alert</button>
Following table shows the options that can be used for alert popup.
Alert Popup Options
Option | Type | Details |
---|---|---|
template | string | Inline HTML template of the popup. |
templateUrl | string | URL of the HTML template. |
title | string | The title of the popup. |
subTitle | string | The subtitle of the popup. |
cssClass | string | The CSS class name of the popup. |
okText | string | The text for the OK button. |
okType | string | The Ionic button type of the OK button. |
Using Prompt Popup
Last Ionic popup that can be created using Ionic is prompt. It has OK button that resolves promise with value from the input and Cancel button that resolves with undefined value.
Controller Code
.controller('MyCtrl', function($scope, $ionicPopup) { $scope.showPrompt = function() { var promptPopup = $ionicPopup.prompt({ title: 'Title', template: 'Template text', inputType: 'text', inputPlaceholder: 'Placeholder' }); promptPopup.then(function(res) { console.log(res); }); }; })
HTML Code
<button class = "button" ng-click = "showPrompt()">Add Popup Prompt</button>
Following table shows options that can be used for prompt popup.
Prompt Popup Options
Option | Type | Details |
---|---|---|
template | string | Inline HTML template of the popup. |
templateUrl | string | URL of the HTML template. |
title | string | The title of the popup. |
subTitle | string | The subtitle of the popup. |
cssClass | string | The CSS class name of the popup. |
inputType | string | The type for the input. |
inputPlaceholder | string | A placeholder for the input. |
cancelText | string | The text for the Cancel button. |
cancelType | string | The Ionic button type of the Cancel button. |
okText | string | The text for the OK button. |
okType | string | The Ionic button type of the OK button. |
Ionic - JavaScript Scroll
The element used for scrolling manipulation in ionic apps is ion-scroll.
Using Scroll
The following code snippets will create scrollable container and adjust scrolling patterns. First we will create our HTML element and add properties to it. We will add > direction = "xy" to allow scrolling to every side, We will also set width and height for the scroll element.
HTML Code
<ion-scroll zooming = "true" direction = "xy" style = "width: 320px; height: 500px"> <div class = "scroll-container"></div> </ion-scroll>
Next we will add image of our world map to div element we created inside ion-scroll and set its width and height.
CSS Code
.scroll-container { width: 2600px; height: 1000px; background: url('../img/world-map.png') no-repeat }
When we run our app, we can scroll the map in every direction. Example below shows North America part of the map.
We can scroll this map to any part that we want. Let's scroll it to show Asia.
There are other attributes that can be applied to ion-scroll. You can check them in the following table.
Scroll Attributes
Attribute | Type | Details |
---|---|---|
direction | string | Possible directions of the scroll. Default value is y |
delegate-handle | string | Used for scroll identification with $ionicScrollDelegate. |
locking | boolean | Used to lock scrolling in one direction at a time. Default value is true. |
paging | boolean | Used to determine if the paging will be used with scroll. |
on-refresh | expression | Called on pull-to-refresh. |
on-scroll | expression | Called when scrolling. |
scrollbar-x | boolean | Should horizontal scroll bar be shown. Default value is true. |
scrollbar-y | string | Should vertical scroll bar be shown. Default value is true. |
zooming | boolean | Used to apply pinch-to-zoom. |
min-zoom | integer | Minimal zoom value. |
max-zoom | integer | Maximal zoom value. |
scrollbar-x | boolean | Used to enable bouncing. Default value on IOS is true, on Android false. |
Infinite Scroll
Infinite scroll is used to trigger some behavior when scrolling pass the bottom of the page. Following example shows how this works. In our controller we created function for adding items to the list. Items will be added when scroll passes 10% of the last element loaded. This will continue until we hit 30 loaded elements. Every time loading is finished, on-infinite will broadcast scroll.infiniteScrollComplete event.
HTML Code
<ion-list> <ion-item ng-repeat = "item in items" item = "item">Item {{ item.id }}</ion-item> </ion-list> <ion-infinite-scroll ng-if = "!noMoreItemsAvailable" on-infinite = "loadMore()" distance = "10%"></ion-infinite-scroll>
Controller Code
.controller('MyCtrl', function($scope) { $scope.items = []; $scope.noMoreItemsAvailable = false; $scope.loadMore = function() { $scope.items.push({ id: $scope.items.length}); if ($scope.items.length == 30) { $scope.noMoreItemsAvailable = true; } $scope.$broadcast('scroll.infiniteScrollComplete'); }; })
There are other attributes that can be used with ion-infinite-scroll
Scroll Attributes
Attribute | Type | Details |
---|---|---|
on-infinite | expression | What should be called when scrolled to the bottom. |
distance | string | The distance from the bottom needed to trigger on-infinite expression. |
spinner | string | What spinner should be shown while loading |
immediate-check | boolean | Should on-infinite be called when screen is loaded. |
Scroll Delegate
Ionic offers delegate for full control of the scroll elements. It can be used by injecting $ionicScrollDelegate service to controller, and then use methods it provides. Example below shows scrollable list of 20 objects.
HTML Code
<div class = "list"> <div class = "item">Item 1</div> <div class = "item">Item 2</div> <div class = "item">Item 3</div> <div class = "item">Item 4</div> <div class = "item">Item 5</div> <div class = "item">Item 6</div> <div class = "item">Item 7</div> <div class = "item">Item 8</div> <div class = "item">Item 9</div> <div class = "item">Item 10</div> <div class = "item">Item 11</div> <div class = "item">Item 12</div> <div class = "item">Item 13</div> <div class = "item">Item 14</div> <div class = "item">Item 15</div> <div class = "item">Item 16</div> <div class = "item">Item 17</div> <div class = "item">Item 18</div> <div class = "item">Item 19</div> <div class = "item">Item 20</div> </div> <button class = "button" ng-click = "scrollTop()">Scroll to Top!</button>
Controller Code
.controller('DashCtrl', function($scope, $ionicScrollDelegate) { $scope.scrollTop = function() { $ionicScrollDelegate.scrollTop(); }; })
When we tap the button, the scroll will be moved to the top.
Now we will go through all of the $ionicScrollDelegate methods.
Delegate Methods
Method | Parameters | Type | Details |
---|---|---|---|
scrollTop(parameter) | shouldAnimate | boolean | Should scroll be animated. |
scrollBottom(parameter) | shouldAnimate | boolean | Should scroll be animated. |
scrollTo(parameter1, parameter2, parameter3) | left, top, shouldAnimate | number, number, integer | First two parameters determine value of the x, and y axis offset. |
scrollBy(parameter1, parameter2, parameter3) | left, top, shouldAnimate | number, number, integer | First two parameters determine value of the x, and y axis offset. |
zoomTo(parameter1, parameter2, parameter3, parameter4) | level, animate, originLeft, originTop | number, boolean, number, number | level is used to determine level to zoom to. originLeft and originRightcoordinates where the zooming should happen. |
zoomBy(parameter1, parameter2, parameter3, parameter4) | factor, animate, originLeft, originTop | number, boolean, number, number | factor is used to determine factor to zoom by. originLeft and originRightcoordinates where the zooming should happen. |
getScrollPosition() | / | / | Returns object with two number as properties: left and right. These numbers represent the distance the user has scrolled from the left and from the top respectively. |
anchorScroll(parameter1) | shouldAnimate | boolean | It will scroll to the element with the same id as the window.loaction.hash. If this element doesn't exist, it will scroll to the top. |
freezeScroll(parameter1) | shouldFreeze | boolean | Used to disable scrolling for particular scroll. |
freezeAllScrolls(parameter1) | shouldFreeze | boolean | Used to disable scrolling for all the scrolls in the app. |
getScrollViews() | / | object | Returns the scrollView object. |
$getByHandle(parameter1) | handle | string |
Used to connect methods to the particular scroll view with the same handle.
$ionicScrollDelegate. $getByHandle('my-handle').scrollTop(); |
Ionic - JavaScript Side Menu
Side menu is one of the most used Ionic components. Side menu can be opened by swiping to the left or right or by triggering the button created for that purpose.
Using Side Menu
First element that we need is ion-side-menus. This element is used for connecting side menu with all screens that will use it. ion-side-menu-contentelement is where the content will be placed and ion-side-menu element is the place where we can put side directive. We will add side menu to index.htmland place ion-nav-view inside side menu content. This way the side menu can be used throughout entire app.
index.html
<ion-side-menus> <ion-side-menu>side = "left"> <h1>SIde Menu</h1> </ion-side-menu> <ion-side-menu-content> <ion-nav-view> </ion-nav-view> </ion-side-menu-content> </ion-side-menus>
Now we will create button with menu-toggle = "left" directive. This button will usually be placed in the apps header bar but we will add it in our template file for the purpose of better understanding. Now when the button is tapped or when we swipe to the right, the side menu will open. You could also set menu-close directive if you would like to have one button only for closing side menu, but we will use toggle button for this.
HTML Template
<button menu-toggle = "left" class = "button button-icon icon ion-navicon"></button>
You can add some additional attributes to ion-side-menus element. enable-menu-with-back-views can be set to false to disable side menu when the back button is showed. This will also hide menu-toggle button from the header. The other attribute is delegate-handle that will be use for connection with $ionicSideMenuDelegate. This will be covered later.
ion-side-menu-content element can use its own attribute. When drag-content attribute is set to false, it will disable ability to open side menu by swiping content screen. edge-drag-threshold attribute has default value of 25. This means that swiping is allowed only 25 pixels from the left and right edge of the screen. We can change this number value or we can set it to falseto enable swiping on entire screen or true to disable it.
ion-side-menu can use side attribute that we showed in example above. It will determine weather the menu should appear from the left or the right side. is-enabled attribute with false value will disable side menu, and widthattribute value is number that represents how wide side menu should be. Default value is 275.
Side Menu Delegate
$ionicSideMenuDelegate is service used for controlling all side menus in the app. We will show you how to use it, and then we will go through all the options available. Like all Ionic services, we need to add it as dependency to our controller and the use it inside controllers scope. Now when we click the button, all of the side menus will open.
Controller Code
.controller('MyCtrl', function($scope, $ionicSideMenuDelegate) { $scope.toggleLeftSideMenu = function() { $ionicSideMenuDelegate.toggleLeft(); }; })
HTML Code
<button class = "button button-icon icon ion-navicon" ng-click = "toggleLeft()"></button>
The following table shows $ionicScrollDelegate methods.
Delegate Methods
Method | Parameters | Type | Details |
---|---|---|---|
toggleLeft(parameter) | isOpen | boolean | Used for opening or closing side menu. |
toggleRight(parameter) | isOpen | boolean | Used for opening or closing side menu. |
getOpenRatio() | / | / | Returns ratio of open part over menu width. If half of the menu is open from the left, the ration will be 0.5. If side menu is closed, it will return 0. If half of the menu is open from the right side, it will return -0.5. |
isOpen() | / | boolean | Returns true if side menu is open, false if it is closed. |
isOpenLeft() | / | boolean | Returns true if left side menu is open, false if it is closed. |
isOpenRight() | / | boolean | Returns true if right side menu is open, false if it is closed. |
getScrollPosition() | / | / | Returns object with two number as properties: leftand right. These numbers represent the distance the user has scrolled from the left and from the top respectively. |
canDragContent(parameter1) | canDrag | boolean | Whether the content can be dragged to open side menu. |
edgeDragThreshold(parameter1) | value | boolean|number | If the value is true, the side menu can be opened by dragging 25px from the edges of the screen. If it is false, dragging is disabled. We can set any number that will represent pixel value from the left and right edge of the screen. |
$getByHandle(parameter1) | handle | string |
Used to connect methods to the particular side menu view with the same handle.
$ionicSideMenuDelegate. $getByHandle('my-handle').toggleLeft(); |
Ionic - JavaScript Slide Box
Slide box contains pages that can be changed by swiping the content screen.
Using Slide Box
The usage of the slide box is simple. You just need to add ion-slide-box as a container and ion-slide with box class inside that container. We will add height and border to our boxes for better visibility.
HTML Code
<ion-slide-box> <ion-slide> <div class = "box box1"> <h1>Box 1</h1> </div> </ion-slide> <ion-slide> <div class = "box box2"> <h1>Box 2</h1> </div> </ion-slide> <ion-slide> <div class = "box box3"> <h1>Box 3</h1> </div> </ion-slide> </ion-slide-box>
.box1, box2, box3 { height: 300px; border: 2px solid blue; }
Output will look like this −
We can change the box by dragging the content to the right. We can also drag to the left to show previous box.
There are various attributes that can be used for controlling slide box behavior.
Delegate Methods
Attribute | Type | Details |
---|---|---|
does-continue | boolean | Should slide box loop when first or last box is reached. |
auto-play | boolean | Should slide box automatically slide. |
slide-interval | number | Time value between auto slide change in milliseconds. Default value is 4000. |
show-pager | boolean | Should pager be visible. |
pager-click | expression | Called when a pager is tapped (if pager is visible). $index is used to match with different slides. |
on-slide-changed | expression | Called when slide is changed. $index is used to match with different slides. |
active-slide | expression | Used as a model to bind the current slide index to. |
delegate-handle | string | Used for slide box identification with $ionicSlideBoxDelegate. |
Slide Box Delegate
$ionicSlideBoxDelegate is service used for controlling all slide boxes. We need to inject it to the controller.
Controller Code
.controller('MyCtrl', function($scope, $ionicSlideBoxDelegate) { $scope.nextSlide = function() { $ionicSlideBoxDelegate.next(); } })
HTML Code
<button class = "button button-icon icon ion-navicon" ng-click = "nextSlide()"></button>
The following table shows $ionicSlideBoxDelegate methods.
Delegate Methods
Method | Parameters | Type | Details |
---|---|---|---|
slide(parameter1, parameter2) | to, speed | number, number | Parameter to represents index to slide to. speed determines how fast is the change in milliseconds. |
enableSlide(parameter1) | shouldEnable | boolean | Used for enambling or disabling sliding. |
previous(parameter1) | speed | number | The value in miliseconds the change should take. |
stop() | / | / | Used to stop the sliding. |
start() | / | / | Used to start the sliding. |
currentIndex() | / | number | Returns index of the curent slide. |
slidesCount() | / | number | Returns total number of the slides. |
$getByHandle(parameter1) | handle | string |
Used to connect methods to the particular slide box with the same handle.
$ionicSlideBoxDelegate.$getByHandle ('my-handle').start(); |
Ionic - Tabs
Tabs are useful pattern for any navigation type or selecting different pages inside your app. The same tabs will appear at the top of the screen for Android devices and at the bottom for IOS devices.
Using Tabs
Tabs can be added to app using ion-tabs as a container element and ion-tabas a content element. We will add it to index.html but you can add it to any HTML file inside your app. Just be sure not to add it inside ion-content to avoid CSS issues that comes with it.
index.html Code
<ion-tabs class = "tabs-icon-only"> <ion-tab title = "Home" icon-on = "ion-ios-filing" icon-off = "ion-ios-filing-outline"></ion-tab> <ion-tab title = "About" icon-on = "ion-ios-home" icon-off = "ion-ios-home-outline"></ion-tab> <ion-tab title = "Settings" icon-on = "ion-ios-star" icon-off = "ion-ios-star-outline"></ion-tab> </ion-tabs>
There is API available for ion-tab elements. You can add it as attributes as showed in example above where we used title, icon-on and icon-off. The last two are used to differentiate selected tab from the rest of it. If you look at the image above, you can see that first tab is selected. You can check the rest of the attributes in the following table.
Tab Attributes
Attribute | Type | Details |
---|---|---|
title | string | The title of the tab. |
href | string | The link used for tab navigation. |
icon | string | The icon of the tab. |
icon-on | string | The icon of the tab when selected. |
icon-off | string | The icon of the tab when not selected. |
badge | expression | The badge for the tab. |
badge-style | expression | The badge style for the tab. |
on-select | expression | Called when tab is selected |
on-deselect | expression | Called when tab is deselected |
hidden | expression | Used to hide the tab. |
disabled | expression | Used to disable the tab. |
Tabs also have its own delegate service for easier control of all the tabs inside the app. It can be injected to controller and contains several methods that are shown in the table below.
Delegate Methods
Method | Parameters | Type | Details |
---|---|---|---|
selectedIndex() | / | number | Returns the index of the selected tab. |
$getByHandle(parameter1) | handle | string |
Used to connect methods to the particular tab view with the same handle. Handle can be added to ion-tabs by usingdelegate-handle = "my-handle" attribute.
$ionicTabsDelegate.$getByHandle('my-handle').selectedIndex(); |
Ionic - Cordova Integration
Cordova offers ngCordova which is set of wrappers specifically designed to work with AngularJS.
Installing ngCordova
When you start Ionic app you will notice that it is using bower. It can be used for managing ngCordova plugins. If you have bower installed skip this step, if you don't then you can install it in command prompt window.
C:\Users\Username\Desktop\MyApp> npm install -g bower
Now we need to install ngCordova. Open your app in command prompt window. Example below is used for the app that is located on desktop and named MyApp
C:\Users\Username\Desktop\MyApp> bower install ngCordova
Next we need to include ngCordova to our app. Open index.html file and add the following scripts. It is important to add these scripts before cordova.js and after ionic scripts.
<script src = "lib/ngCordova/dist/ng-cordova.js"></script>
Now we need to inject ngCordova as angular dependency. Open your app.js file and add the ngCordova to angular module. If you used one of the Ionic template apps, you will notice that there are already injected ionic, controllers and services. In that case you will just add ngCordova at the and of array.
angular.module('myApp', ['ngCordova'])
You can always check the plugins that are already installed by typing −
C:\Users\Username\Desktop\MyApp> cordova plugins ls
Ionic - Cordova AdMob
This plugin is used for integrating ads natively. We will use admobpro plugin in this tutorial since the admob is deprecated.
Using AdMob
To be able to use ads in your app, you need to sign up to admob and create a banner. When you do this, you will get Ad Publisher ID. You will need it later in this tutorial. Since these steps aren't part of Ionic framework, we will not explain it in this tutorial. You can follow steps by Google support team here. You will also need to have android or ios platform installed since the cordova plugins work only on native platforms. We already showed you how to do this in our environment setup tutorial.
AdMob plugin can be installed in command prompt window.
C:\Users\Username\Desktop\MyApp> cordova plugin add cordova-plugin-admobpro
Now that we installed the plugin we need to check if device is ready before we are able to use it. This is why we need to add the following code in $ionicPlatform.ready function inside app.js.
if( ionic.Platform.isAndroid() ) { admobid = { // for Android banner: 'ca-app-pub-xxx/xxx' // Change this to your Ad Unit Id for banner... }; if(AdMob) AdMob.createBanner( { adId:admobid.banner, position:AdMob.AD_POSITION.BOTTOM_CENTER, autoShow:true } ); }
The same code can be applied for IOS or windows phone. You will only use different id for these platforms. Instead of banner you can use interstitial ads that will cover entire screen.
The following table shows methods that can be used with admob.
Method | parameters | Details |
---|---|---|
createBanner(parameter1, parameter2, parameter3) | adId/options, success, fail | Used for creating the banner. |
removeBanner() | / | Used for removing the banner. |
showBanner(parameter1) | position | Used for showing the banner. |
showBannerAtXY(parameter1, parameter2) | x, y | Used for showing the banner at specified location. |
hideBanner(); | / | Used for hiding the banner. |
prepareInterstitial(parameter1, parameter2, parameter3) | adId/options, success, fail | Used for preparing interstitial. |
showInterstitial(); | / | Used for showing interstitial. |
setOptions(parameter1, parameter2, parameter3) | options, success, fail | Used for setting the default value for other methods. |
There are also the events that can be used.
Event | Details |
---|---|
onAdLoaded | Called when the ad is loaded. |
onAdFailLoad | Called when the ad is failed to load. |
onAdPresent | Called when the ad will be showed on screen. |
onAdDismiss | Called when the ad is dismissed. |
onAdLeaveApp | Called when the user leaves the app by clicking the ad. |
You can handle these events by following the example below.
document.addEventListener('onAdLoaded', function(e){ // Handle the event... });
No comments:
Post a Comment