step by step from idea through prototyping to the app
stores
Nikola Brežnjak
This book is for sale athttp://leanpub.com/ionic-framework
This version was published on 2015-12-15
This is aLeanpubbook. Leanpub empowers authors and publishers with the Lean Publishing process.Lean Publishingis the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do.
How to get started with Ionic framework on Mac and Windows . . . . 1
Why should you listen to me? . . . 1
Introduction . . . 3
Ways you can make an app these days . . . 5
What is Ionic and why it’s so good . . . 7
Installing prerequisites for both Mac and Windows . . . 8
Installing Ionic . . . 12
Using Ionic CLI . . . 13
Starting a project with Ionic by using the existing templates . . . 14
Running the Ionic application . . . 16
Conclusion . . . 18
How to create a calculator application with Ionic framework by using Ionic Creator for UI . . . 19
Introduction . . . 19
Calculator interface mockup . . . 21
Calculator interface prototype . . . 22
Starting a project with Ionic CLI by using the template made in Ionic Creator . . . 30
Ionic application folder structure . . . 33
Refactoring our application . . . 38
Calculator logic with controllers . . . 46
Finishing the calculator template . . . 48
Run the application . . . 49
Conclusion . . . 50
How to polish our existing calculator application . . . 51
Sanitization check . . . 51
Design changes . . . 53
How to create icons and splash screen images automatically in Ionic framework . . . 58
How to implement Google AdMob ads . . . 69
How to use Ionic.io cloud service to share our application with other users without going through the app store . . . 79
How to test our application on the real physical devices and emulators . . . 84
How to publish our calculator application to the Apple’s App Store and Google’s Play
Store . . . 102
Google Play Store . . . 102
Apple App Store . . . 115
Conclusion . . . 132
framework on Mac and Windows
This is the first post in a series of posts which will teach you how to take advantage of your web development knowledge in building hybrid applications for iOS and Android.
This first post explains:
• How to make an app these days • What actually is Ionic framework
• How to install Ionic on both Mac and Windows • How to use Ionic CLI to start an Ionic project • How to run an Ionic application
Why should you listen to me?
If you’re likeThen let me share with you my current (YMMV¹based on the time of your visit) StackOverflow profile²image:
You can clearly see that I’m the top answerer in theionictag for the last month and in the top 10
answerers of all time. If you want to see what those answers actually are, you can take a look at
my StackOverflow profile³. Also, I’m the guy behind theMEAN stack series⁴here on HackHands,
¹http://www.urbandictionary.com/define.php?term=ymmv ²http://stackoverflow.com/users/534755/nikola?tab=profile ³http://stackoverflow.com/users/534755/nikola?tab=answers ⁴https://hackhands.com/how-to-get-started-on-the-mean-stack/
with a self-published (pay what you want)Getting MEAN with MEMEs⁵blog2book at Leanpub. If that’s not enough, I’m currently a technical reviewer for the book “Getting started with Ionic” by PacktPub, and also a technical reviewer for the video “Rapid Ionic”, also by PacktPub. Anyways, if nothing else, give it a shot with my unique “humorly” approach, and you just might like it and learn something.
Ok, enough about me, let’s teach you some Ionic, since
Introduction
85% of mobile time is spent in apps
You’re bombarded with reportsall⁶ over⁷ the⁸ web⁹that users tend to spend way more time on their
⁵https://leanpub.com/meantodo
⁶http://www.theguardian.com/technology/appsblog/2014/apr/02/apps-more-popular-than-the-mobile-web-data-shows ⁷http://www.smartinsights.com/mobile-marketing/mobile-marketing-analytics/mobile-marketing-statistics/
⁸http://venturebeat.com/2013/04/03/the-mobile-war-is-over-and-the-app-has-won-80-of-mobile-time-spent-in-apps/ ⁹http://techcrunch.com/2015/06/22/consumers-spend-85-of-time-on-smartphones-in-apps-but-only-5-apps-see-heavy-use/
phones and especially in apps (rather than surfing the web using their phones) and you decided that it’s time to learn how to make an app.
If you’re a web developer, you have a decent knowledge of HTML, CSS, and JavaScript; also, you’re most likely using one of the ever so slightly popular frameworks these days like AngularJS, Ember or React, just to name a few. If you’re even proficient enough with the MEAN stack, you are a well-rounded full stack developer, and you basically have it all. Well, except the apps part, right?
If you want to see what’s all that fuss about the MEAN stack, you can check out the free four part tutorial series here on HackHands, starting with the first post onHow to get started on the MEAN stack¹⁰.
But, where to start with making an app? Could you use some of your existing skills? Up until fairly recently, if you wanted to make an app for (currently) two most popular mobile operating systems (iOS and Android) your only bet was to make the, so-called, native application by using the SDKs of the intended platforms.
This, of course, meant that you needed to make two versions of your application; one for iOS and one for Android. If you are a solo developer, chances that you’re proficient in both are not so great. Therefore, for some time, developers were opting for either iOS or Android, whereas big firms had two developing departments, one for each platform (worth mentioning Windows phone here as well).
Nowadays, luckily, with the Ionic Framework (and few others likePhoneGap¹¹,OnsenUI¹²,Famo.us¹³) you can create one application by using the skills you, as a web developer, already have (others, don’t fret - this isn’t rocket science to be afraid of it) and then deploy this one codebase as an app to both iOS and Android stores. How cool is that, right? You can see the comparison review between the noted frameworkshere¹⁴.
¹⁰https://hackhands.com/how-to-get-started-on-the-mean-stack/ ¹¹http://phonegap.com/
¹²http://onsen.io/ ¹³http://famous.org/
Ways you can make an app these days
We’ve kind of touched all three in the Introduction section, but let’s keep it nice and concise and list them here too. So, there are actually 3 ways that you can make an application for mobile devices these days:
• Native app • Mobile website • Hybrid app
Now, let’s talk a bit more about the pros and cons of each of them.
Native app
As mentioned previously, you can make an app specifically for iOS and Android by using their specific SDKs. If you want to build a native application for iOS you have to:
• have a Mac computer. Sure, there are ways around it, but I honestly don’t recommend them; for starters, a cheap Mac Mini will do just fine - at least it did so in my case
• downloadXcode¹⁵from the App Store (it’s actually free)
• buy theApple Developer license¹⁶that costs 99$ per year (if you want to publish to the App Store; and dooh!, you do)
You can write the apps by using the languageSwift¹⁷, or it’s predecessorObjectiveC¹⁸.
If we’re honest here, I think that Swift is a great step up from the clunky ObjectiveC, but that’s just my own opinion (some people, of course,disagree¹⁹). Anyways, if you ever decide to go native just make sure you go with Swift as you’ll get to know your way around it way sooner than with ObjectiveC, especially if you have a background in web development.
If you want to build a native application for Android you have to: • have any computer
• download the appropriate SDKs (we’ll cover this in the next section) • buy theGoogle Developer license²⁰which is 25$ per year
One of the pros of a native applications would be it’s speed and direct access to a native API (you don’t have to use any middleman wrappers, like in hybrid apps). A definite con of a native applications is that you need to build two (or more) applications, one for each desired platform.
¹⁵https://developer.apple.com/xcode/ ¹⁶https://developer.apple.com/programs/ ¹⁷https://developer.apple.com/swift/ ¹⁸https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html ¹⁹http://www.infoworld.com/article/2968287/application-development/stop-the-funeral-apple-swift-versus-objective-c-alive-and-kicking.html ²⁰https://play.google.com/apps/publish/signup/
Mobile website
Mobile website is actually a “normal” website (yeah, don’t go jumping because of the terminology; you’re smart, you get the point) that you visit with your browser on your phone, designed specifically to adapt to your phone’s screen. As we’ve noted in the Introduction section, researches show that in todays world mobile websites tend to have a way lower engagement than they used to.
Developers used to make specific sites just for mobile browsers (on it’s own domain; usually m.domain.com) but this proved to be hard to maintain. A practice called responsive website design²¹ is used these days, where you basically have one HTML codebase, and you determine the look for specific devices (based on resolutions) by using the so-calledmedia queries²².
A great example of a mobile framework isjQuery mobile²³that is soon coming out with its new 1.5 version, so we’ll see if they bring something new to the table. From my personal experience with the framework from two years ago, I have all but good words for it; so, definitely use it if you’re “only” making a mobile version of your web application.
A definite advantage of the mobile websites is that you can update them as you see fit, without waiting for the approval from Apple or Google. One of the disadvantages are definitely the fact that the mobile websites these days have way lower engagement than they used to, and that you can’t basically use any of the additional phone features like for example camera or GPS.
Hybrid app
A hybrid app is a bassicaly a mobile application, written with the same languages that you use when building websites, with the addition that it contains an isolated browser instance, called WebView, which runs this web application inside of a native app. Hybrid apps can access the mobile device and use the additional phone features like for example camera or GPS.
Definite advantage of the hybrid apps is the fact that you can access the additional phone features via plugins and that you can do all the development with the same set of skills as you use when developing “normal” web applications. One of the disadvantages is the fact that, even though it’s improving, the so-called Web View has it’s limitations in terms of speed. So, it might not be best suited if you’re on a quest to make the next best game with full blown 3D graphics.
What is Ionic and why it’s so good
As I gave ananswer on StackOverflow²⁴:²¹https://developers.google.com/web/fundamentals/layouts/rwd-fundamentals/ ²²https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries ²³https://jquerymobile.com/
Disclaimer: This will sound like advertisement, so I have to say I’m in no way affiliated with Ionic, I just happen to like it so much that I’m sharing the love for it.
Ionic is so much more than “just” an UI framework. Ionic allows you to:
• generate icons and splash screens for all devices and device sizes with a single command: ionic resources. This alone saves you at least a day of image
preparing for various sizes.
• instantly update your apps with code changes, even when running directly on your device withionic run --livereload
• build and test iOS and Android versions side-by-side and see changes instantly withionic serve --lab
• share your Ionic apps with clients, customers, and testers all around the world without ever going through the App Store withionic share
• easily access the full native functionality of the device using ngCordova (here you get to use any Cordova plugin) Also, Drifty²⁵ (the team behind the Ionic framework) is building a full-stack backend services and tools for your Ionic app like Deploy (for deploying a new version without going through Apple review process! - this is huge!),Analytics²⁶,Push notifications²⁷. Ionic CLI (command line interface) uses Cordova in the backend and allows you to build (directly using Ionic CLI) apps for iOS and Android (just by doingionic build ios or ionic build android). Ionic uses Angular as a frontend framework so if you’re familiar
with it, it will come as a bonus. They’re working closely with the Angular 2.0 team²⁸too. All in all, I personally think Ionic framework has a bright future, so if nothing else – give it a try I bet you’ll like the ease of making an app with it.
Do I have your attention now? Great, let’s install all the needed prerequisites in the next section and start using Ionic!
Installing prerequisites for both Mac and Windows
We need to have Node.js and Git installed in order to install both Ionic and Cordova. If you already have (and if you’re a web developer chances are that you do) these tools installed, you can skip this section, and go straight to installing Ionic.
Installing Node.js
In order to download Node.js, visit http://nodejs.org/download/²⁹, where you’ll see the following options: ²⁵http://drifty.com/ ²⁶http://www.nikola-breznjak.com/blog/ionic/ionic-analytics-alpha-lets-you/ ²⁷http://blog.ionic.io/announcing-ionic-push-alpha/ ²⁸http://blog.ionic.io/angular-2-ionic/ ²⁹http://nodejs.org/download/
Installation on Windows and Mac OS is simple as you just have to download and run the appropriate installer and follow the familiar instructions (next, next, next, sure I accept, next, finish).
If you havebrewon your Mac then you can also install Node.js with: brew install node
In both cases,npm(Node Package Manager - used to install other packages) will be installed along
with Node.js.
in your Command prompt (or, even better, useConsole 2³⁰):
node -v
You should get an output similar to:
v0.12.7
To verify that you installed Node.js correctly on your Mac, run the same command as above in your Terminal (or, even better, useiTerm³¹), and you should get the same similar output as above.
Installing Git
In order to install Git, visithttp://git-scm.com/download³², where you’ll see the following options:
Installation on Windows and Mac OS is as simple as for Node.js as you just have to download and run the appropriate installer and follow the, yet again, familiar instructions.
To verify that you installed Git correctly on your Windows/Mac machine, run the following command in your Command prompt/Terminal:
git
You should get an output similar to:
³⁰http://www.nikola-breznjak.com/blog/quick-tips/customize-console-2-on-windows-machine/ ³¹https://www.iterm2.com/
1 usage: git [--version] [--help] [-C <path>] [-c name=value]
2 [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
3 [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]
4 [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
5 <command> [<args>]
6
7 The most commonly used git commands are:
8 add Add file contents to the index
9 bisect Find by binary search the change that introduced a bug
10 branch List, create, or delete branches
11 checkout Checkout a branch or paths to the working tree
12 clone Clone a repository into a new directory
13 commit Record changes to the repository
14 diff Show changes between commits, commit and working tree, etc
15 fetch Download objects and refs from another repository
16 grep Print lines matching a pattern
17 init Create an empty Git repository or reinitialize an existing one
18 log Show commit logs
19 merge Join two or more development histories together
20 mv Move or rename a file, a directory, or a symlink
21 pull Fetch from and integrate with another repository or a local branch
22 push Update remote refs along with associated objects
23 rebase Forward-port local commits to the updated upstream head
24 reset Reset current HEAD to the specified state
25 rm Remove files from the working tree and from the index
26 show Show various types of objects
27 status Show the working tree status
28 tag Create, list, delete or verify a tag object signed with GPG
29
30 'git help -a' and 'git help -g' list available subcommands and some
31 concept guides. See 'git help <command>' or 'git help <concept>'
32 to read about a specific subcommand or concept.
You don’t have to worry if you don’t know how to use Git since you won’t be needing it directly (npm uses it download packages). However, if you would like to learn (and there’s no reason why you shouldn’t expand your knowledge), you can check out thisgood interactive tutorial³³made by CodeSchool.
Installing Ionic
If you’ve installed the needed prerequisites from the previous section, then in order to install Ionic (both on Mac and Windows) you just have to run the following command:
npm install ionic cordova -g
Ionic uses Cordova in the background, thus the need for it. We’re using the -g flag here, in order to install the packages ionic and cordovaglobally³⁴.
To verify that you’ve installed Ionic correctly on your Windows/Mac machine, run the following command in your Command prompt/Terminal:
ionic -v
You should get an output similar to:
1.6.4
To verify that you’ve installed Cordova correctly on your Windows/Mac machine, run the following command in your Command prompt/Terminal:
cordova -v
You should get an output similar to:
4.2.0
If you had Node.js installed before (and haven’t used it much since), you may get a notification like this:
1 ******************************************************
2 Upgrade warning - for the CLI to run correctly,
3 it is highly suggested to upgrade the following:
4
5 Please update your Node runtime to version >=0.12.x
6 ******************************************************
To resolve this issue, just update Node.js; either by re-downloading it (on Windows) or by executing the following command in the Terminal (on a Mac):
brew update; brew upgrade node
I would like to take a moment here and encourage you that you post a comment about any problems you may have (and from my experience from StackOverflow there tends to be quite of them) with these (seemingly simple) installation tasks. There always tends to be some older version of Node.js installed, or problems with cache and npm, blah blah blah… I will do my best to try to resolve your issue.
Using Ionic CLI
If you runionicin your Terminal/Command prompt you will get an output similar to the one below:
1 > ionic 2 _ _ 3 (_) (_) 4 _ ___ _ __ _ ___ 5 | |/ _ \| '_ \| |/ __| 6 | | (_) | | | | | (__ 7 |_|\___/|_| |_|_|\___| CLI v1.6.4 8
9 Usage: ionic task args
10
11 =======================
12
13 Available tasks: (use --help or -h for more info)
14
15 start ... Starts a new Ionic project in the specified PATH
16 serve ... Start a local development server for app dev/testing
17 platform ... Add platform target for building an Ionic app
18 run ... Run an Ionic project on a connected device
19 emulate ... Emulate an Ionic project on a simulator or emulator
20 build ... Locally build an Ionic project for a given platform
21 plugin ... Add a Cordova plugin
22 resources ... Automatically create icon and splash screen resources (bet\
23 a)
24 Put your images in the ./resources directory, named splash or icon.
25 Accepted file types are .png, .ai, and .psd.
26 Icons should be 192x192 px without rounded corners.
27 Splashscreens should be 2208x2208 px, with the image centered in the\
28 middle.
29
30 upload ... Upload an app to your Ionic account
31 share ... Share an app with a client, co-worker, friend, or customer
32 lib ... Gets Ionic library version or updates the Ionic library
33 setup ... Configure the project with a build tool (beta)
34 io ... Integrate your app with the ionic.io platform services (al\
35 pha)
36 push ... Upload APNS and GCM credentials to Ionic Push (alpha)
37 config ... Set configuration variables for your ionic app (alpha)
39 service ... Add an Ionic service package and install any required plug\
40 ins
41 add ... Add an Ion, bower component, or addon to the project
42 remove ... Remove an Ion, bower component, or addon from the project
43 list ... List Ions, bower components, or addons in the project
44 ions ... List available ions to add to your project
45 templates ... List available Ionic starter templates
46 info ... List information about the users runtime environment
47 help ... Provides help for a certain command
48 link ... Sets your Ionic App ID for your project
49 hooks ... Manage your Ionic Cordova hooks
50 state ... Saves or restores state of your Ionic Application using th\
51 e package.json file
52 docs ... Opens up the documentation for Ionic
What you got is actually a nice summary of all the commands that you can run using the ionic CLI, along with their short descriptions. Btw, if you’re wondering what this CLI thing is (and you haven’t Googled it yet³⁵); it’s actually an acronym from Command Line Interface, and in Ionic terms it’s actually a tool that makes it easier tostart, build, run, and emulate, (and a lot more), Ionic apps³⁶. In the following chapters we will cover most of these commands, but for now let’s not burden you too much, and let’s do a quick skin deep dive by making a simple project usingionic startcommand.
Starting a project with Ionic by using the existing
templates
Cool, you’ve made it so far - I promise, you’re going to see some code now!
Ionic CLI allows us to start and initialize your project by using the aforementioned ionic start
command. If you take a look at the official documentation for the start command³⁷ you will see something like the following definition:
ionic start appname [template]
If you just runionic start appname the Ionic CLI will make a bootstrap application with all the
needed parts in the appname folder, with the so-called blank template. There are three named template starters: blank, sidemenu, and tabs.
Additionally, you can use Github repo starters and Codepen URL starters. For a comprehensive list of (currently 20) starter apps check out the post from my friend Dragan over atGajotres³⁸.
³⁵https://en.wikipedia.org/wiki/Command-line_interface ³⁶http://ionicframework.com/docs/cli/
³⁷http://ionicframework.com/docs/cli/start.html
In our example, we will use the sidemenu template, so execute the following command from your Terminal/Command prompt:
ionic start Ionic_1stTutorial sidemenu
You should see something similar to the following output:
1 C:\Users\Nikola\Desktop\IonicTesting>ionic start Ionic_1stTutorial sidemenu
2 Creating Ionic app in folder C:\Users\Nikola\Desktop\IonicTesting\Ionic_1stTutor\
3 ial based on sidemenu project
4 Downloading: https://github.com/driftyco/ionic-app-base/archive/master.zip
5 [=============================] 100% 0.0s
6 Downloading: https://github.com/driftyco/ionic-starter-sidemenu/archive/master.z\
7 ip
8 [=============================] 100% 0.0s
9 Updated the hooks directory to have execute permissions
10 Update Config.xml
11 Initializing cordova project
12
13 Your Ionic project is ready to go! Some quick tips:
14 * cd into your project: $ cd Ionic_1stTutorial
15 * Setup this project to use Sass: ionic setup sass
16 * Develop in the browser with live reload: ionic serve
17 * Add a platform (ios or Android): ionic platform add ios [android]
18 Note: iOS development requires OS X currently
19 See the Android Platform Guide for full Android installation instructions:
20 https://cordova.apache.org/docs/en/edge/guide_platforms_android_index.md.html
21 * Build your app: ionic build <PLATFORM>
22 * Simulate your app: ionic emulate <PLATFORM>
23 * Run your app on a device: ionic run <PLATFORM>
24 * Package an app using Ionic package service: ionic package <MODE> <PLATFORM>
25
26 For more help use ionic --help or ionic docs
27 Visit the Ionic docs: http://ionicframework.com/docs
28
29 New! Add push notifications to your Ionic app with Ionic Push (alpha)!
30 https://apps.ionic.io/signup
31 +---+
32 + New Ionic Updates for August 2015
33 +
34 + The View App just landed. Preview your apps on any device
35 + http://view.ionic.io
36 +
38 + ionic share EMAIL
39 +
40 + Generate splash screens and icons with ionic resource
41 + http://ionicframework.com/blog/automating-icons-and-splash-screens/
42 +---+
Running the Ionic application
Now that we’ve initialized our Ionic application based on the sidemenu template, we have to run it in order to see what Ionic CLI generated for us.
First, change the directory to the name of the application you gave in theionic startcommand.
In our case, that is Ionic_1stTutorial:
1 C:\Users\Nikola\Desktop\IonicTesting\Ionic_1stTutorial>```
2
3 If you open up the project in your editor (I use [Sublime Text 3](http://www.sub\
4 limetext.com/3)) you will see the following folder structure:
5
6 
7
8 In the following chapters, we will spend most of the time in the **www** folder.
9
10 > Since Ionic is based on [AngularJS](https://angularjs.org/) framework, you wil\
11 l need at least a basic understanding of it, and you can start exploring it with\
12 a [free interactive tutorial](http://angular.codeschool.com/) by CodeSchool. Al\
13 so, you can take a look at my [fourth tutorial in the MEAN stack](https://hackha\
14 nds.com/finishing-Angular-TODO-application-deploying-production/) series, which \
15 is all about AngularJS.
16
17 There are few ways in which you can get your Ionic application running:
18
19 + `ionic serve` - starts the app in a local web browser
20 + `ionic emulate android` - starts the app in an emulator (in this example andro\
21 id is used; you can also use **ios** if you're on a Mac and have all the prerequ\
22 isites installed)
23 + `ionic run android` - starts the app on the actual device that's plugged into \
24 your computer
25 + `ionic build android` - creates an **.apk** file which you can physically copy\
26 to your Android device and run it (this scenario doesn't work for iOS devices i\
27 n normal circumstances; you have to go through Xcode, as we'll describe in detai\
29
30 So, now run the following command in your Terminal/Command prompt:
31
32 `ionic serve`
33
34 You should see the following similar output:
C:UsersNikolaDesktopIonicTestingIonic_1stTutorial>ionic serve Running live reload server: http://localhost:35729 Running dev server: http://localhost:8100 Ionic server commands, enter: restart or r to restart the
client app from the root goto or g and a url to have the app navigate to the given url consolelogs or c to enable/disable console log output serverlogs or s to enable/disable server log output quit or q to shutdown the server and exit
ionic $ “‘
Also, you should get your local browser started up automatically, pointing to the address http://localhost:8100/#/app/playlists, with an output similar to the one on the image below (I resized the window for clarity - if you’re
using Chrome³⁹, you can get the use the Window Resizer plugin⁴⁰, or use the Chrome Dev Tools Emulate feature⁴¹):
³⁹https://www.google.com/chrome/
⁴⁰https://chrome.google.com/webstore/detail/window-resizer/kkelicaakdanhinjdeammmilcgefonfh ⁴¹https://developer.chrome.com/devtools/docs/device-mode
Awesome thing about this is that you have automatically set up live reload feature, which means that as soon as you change the code in your www folder, the application will reload automatically so that you don’t have to keep pressing the F5 (+R) key on your Windows (Mac) machine.
If you like, you can get this project onGithub⁴².
Conclusion
In this chapter we’ve gone through the options that you have in making an app these days. Then we explained what actually is Ionic framework and how to install it on both Mac and Windows. With the use of the Ionic CLI we started a project based on the sidemenu template, and finally we ran it locally in the browser with the use ofionic servecommand. In the next chapter I’ll show you how
to create your own calculator application by making use of Ionic Creator.
application with Ionic framework by
using Ionic Creator for UI
This is the second post in a series of posts which will teach you how to take advantage of your web development knowledge in building hybrid applications for iOS and Android. The first post in this series was all about How to get started with Ionic framework on Windows and Mac⁴³.
This second post explains:
• How to create a calculator interface mockup
• How to create a calculator interface prototype without coding by using Ionic Creator • How to start the Ionic application based on the created interface
• Which are the most important folders and files and what is the starting point of the application • How to create the calculator logic by using controllers
Finished project:
• clone the code fromGithub⁴⁴
• in the project directory executeionic serveto run the project locally in your browser
• you can check out thelive example⁴⁵of this application
Introduction
Since there are not so many Calculator applications in the App store (around 500 according to my search shown on the image below), who knows, you just may create your own bestseller in this category, if you add a needed tweak or two.
⁴³
⁴⁴https://github.com/Hitman666/Ionic_2ndTutorial ⁴⁵http://nikola-dev.com/IonicCalculator/mobile.html
All jokes and hopes aside, this seemed to be a decent “more serious”, but still easy to acomplish, task. Let’s start this chapter by creating the interface for our application.
Calculator interface mockup
Before starting any application, we should know what we want (well, at least in general). We should know what problem are we trying to solve with our application and how are we going to solve it. Also, we would need to have a decent idea of how we would want our application to look like. The answer to the first two questions would be rather easy; the problem is that we can’t do calculations fast enough in our mind (well, except if you’reArthur Benjamin⁴⁶) and we need a tool to help us with that. Surely, there are specific calculator devices, but it would be too cumbersome to carry one with us all the time.
Besides, since these days almost everyone has a smartphone, it turns out it would be an awesome idea to make an app for it. Because, as they say:
there’s an app for that
where that is basically everything these days. If you find that there isn’t an app for some particular problem that you may have, that just may be your lucky break. Who knows, you just may end up having your 5 minutes of fame on the AppStore, until another clone of your app pushes you away. Anyways, back to our calculator application; we don’t need any fancy options (at least not yet, in this 1.0 version), we’ll just stick with the basic mathematical operations like adding, substracting, dividing and multiplying.
These basic operations will be our MVP (Minimal Viable Product), as the author Eric Ries explains in his awesome (and highly recommended) bookLean Startup⁴⁷. We can always add features later, if it turns out that our idea was good. Or, we can pivot away from it, if it turns out it was not a next best thing after Flappy Bird, by not spending too much time and money building the app with dozen of features which in end would not be used at all.
As for the user interface, you can use various tools that help with mocking up your application’s user interface (Balsamiq Mockups⁴⁸,Mockingbird⁴⁹,Mockup Builder⁵⁰, etc.), but I tend to be old school about it and I made a little hand drawing of how I imagined the app should look like, and this is what I came up with after few attempts:
⁴⁶https://www.youtube.com/watch?v=e4PTvXtz4GM
⁴⁷http://www.nikola-breznjak.com/blog/books/the-lean-startup-eric-ries/ ⁴⁸https://balsamiq.com/products/mockups/
⁴⁹https://gomockingbird.com/home ⁵⁰http://mockupbuilder.com/
Note: As you can see there’s no comma in our mockup, basically because we’re just trying to keep it simple here.
Calculator interface prototype
Now that we know what our application needs to do, and how it basically has to look like, lets start by creating our interface.
We could create our interface by manually entering HTML, but we’re going to show a different approach here - the one which usesIonic Creator⁵¹, which is an awesome web application that lets you drag&drop components that make up the user interface. As such, this is a great tool which helps in quick user interface prototyping.
The best thing is that you can then just download the created HTML and use it directly in your Ionic application. Of course, some additional changes will be needed later in the HTML and CSS code, but for creating a quick prototype this will be great.
Worth noting is that there are currently on the market lots of other tools for interface prototyping (InVision⁵²,Flinto⁵³,Mockup Builder⁵⁴, etc.), however these tools don’t (at least not yet) have a
“one-⁵¹https://creator.ionic.io/ ⁵²http://www.invisionapp.com/ ⁵³https://www.flinto.com/ ⁵⁴http://mockupbuilder.com/
click download and ready for your Ionic” option like Ionic Creator does.
Creating calculator interface with Ionic Creator
In order to useIonic Creator⁵⁵you have to signup/login on their website. The first time you log in, you’ll be asked for additional info like Company or phone, but you can safely skip that. In the initial screen you will be asked to name your application (I chose IonicCalculator):
The main screen of the Ionic Creator application looks like the one shown on the image below:
In the upper left hand side you’ll see the PAGES panel and inside it you’ll see Page item. Click on Page, and on the right hand side change the TITLE to Calculator. Next, remove the PADDING by switching off the slider. The way this should look like now is shown on the image below:
First, we need some kind of a “display” which will show the numbers that we’re clicking. Ideally, we would use a<label>component, however it’s not available in the Ionic Creator as of yet. So, for
this we will use the<input>element, and we can easily adjust this later when we’ll download the
generated HTML code.
Ionic Creator works in a drag&drop kind of way, which basically means that you can drag any component from the Componenes pane on the left hand side and drop it on the actual Phone image in the center of the screen.
Since we concluded that we’ll use the Input element, we can try to drag&drop it to the Phone, but that won’t work. First you need to drag the Form component on the page, and then on it you should drag&drop the Input component as well.
before) and change its PLACEHOLDER to 0 (zero digit) and NAME to display. The way this should look like now is shown on the image below:
Next, according to our mockup, we should add buttons that would represent the digits from 0 to 9, and the buttons that would represent adding (+), substracting (-), multiplying (x) and dividing (/) operations. Also, we will need the equals button (=) and a clear button (C).
In the first row we need to have 4 buttons, the ones representing digits 7, 8, 9 and one representing a dividing operation. To acomplish this, we will use a Button Bar component from the Components panel so that we’ll drag&drop it just below the Input field on the screen. You should see something like this now in your Ionic Creator window:
As you can see from the previous image, three buttons were added inside the Button Bar component. Click on a button with text 1 and change it to 7. Repeat the process for other two buttons by changing the text to 8 and 9, respectively.
Ionic Creator adds 3 buttons within the Button Bar, but we need the 4th one. So, to add it, drag&drop a Button component next to the button which you labeled as 9. Click on this newly added button and change its text to /, and its style to Energized. Your interface should look like the one on the image below:
Repeat the process by adding next three rows:
• buttons representing 4, 5, 6 and a button representing multiplication (x) • buttons representing 1, 2, 3 and a button representing subtraction (-) Your interface should look like the one on the image below:
• one button representing the Clear operation (C), with theAssertivestyle
• one button representing 0
• one button representing the equals operation (=), with thePositivestyle
• one button representing the addition operation (+), with the ‘Energized style Your interface should look like the one on the image below:
Don’t worry about the slight missalignement or paddings, we’ll take care of this in the next chapter when we’ll be polishing our application and preparing it for the App/Play store.
So, basically this is it, we have our interface ready and now we can export it by clicking on the Export icon in the header, as shown on the image below:
Starting a project with Ionic CLI by using the template
made in Ionic Creator
From the previous image we see that we have three options (Ionic CLI, ZIP file, and Raw HTML) to start our application based on the mockup we created in Ionic Creator. We’re going to use the Ionic CLI option, by running the following command from our Terminal/Command prompt:
ionic start Ionic_2ndTutorial creator:167ff268a01d
Note: if you followed this chapter by creating the interface in Ionic Creator yourself, then you will have a different creator number. Of course, you’re free to use mine if you wish to do so. Also, you’re free to name your project any way you want, I chose Ionic_2ndTutorial in this example.
After you execute the upper command in your terminal, you should see something similar to the following output:
1 C:\Users\Nikola\Desktop\IonicTesting>ionic start Ionic_2ndTutorial creator:167ff\
2 268a01d
3 Creating Ionic app in folder C:\Users\Nikola\Desktop\IonicTesting\Ionic_2ndTutor\
4 ial based on creator:167ff268a01d project
5 Downloading: https://github.com/driftyco/ionic-app-base/archive/master.zip
6 [=============================] 100% 0.0s
7
8 Downloading Creator Prototype: https://apps.ionic.io\api\v1\creator\167ff268a01d\
9 \download\html
10 Updated the hooks directory to have execute permissions
11 Update Config.xml
12 Initializing cordova project
13
14 Your Ionic project is ready to go! Some quick tips:
15 * cd into your project: $ cd Ionic_2ndTutorial
16 * Setup this project to use Sass: ionic setup sass
17 * Develop in the browser with live reload: ionic serve
18 * Add a platform (ios or Android): ionic platform add ios [android]
19 Note: iOS development requires OS X currently
20 See the Android Platform Guide for full Android installation instructions:
21 https://cordova.apache.org/docs/en/edge/guide_platforms_android_index.md.html
22 * Build your app: ionic build <PLATFORM>
23 * Simulate your app: ionic emulate <PLATFORM>
24 * Run your app on a device: ionic run <PLATFORM>
25 * Package an app using Ionic package service: ionic package <MODE> <PLATFORM>
26
27 For more help use ionic --help or ionic docs
28
29 Visit the Ionic docs: http://ionicframework.com/docs
30
31 New! Add push notifications to your Ionic app with Ionic Push (alpha)!
32 https://apps.ionic.io/signup
33 +---+
34 + New Ionic Updates for August 2015
35 +
36 + The View App just landed. Preview your apps on any device
37 + http://view.ionic.io
38 +
39 + Invite anyone to preview and test your app
40 + ionic share EMAIL
41 +
43 + http://ionicframework.com/blog/automating-icons-and-splash-screens/
44 +---+
As per the instruction in the output above let’scdinto our project: cd Ionic_2ndTutorial
Now, let’s see how this application looks like in the browser by executing the following command in the Terminal/Command prompt:
ionic serve
You should be familiar with this command from the first chapter, and if not please take a look at it first. For those short in time, basicallyionic serve starts up a local web
browser and shows how our application would look like; which, actually is great for rapid development since you get to see changes instantly without needing to reload your browser.
We should see something similar to the image below:
Btw, the ruller and the Device setting (Apple iPhone 6) are a part of an awesome Developer tools in Chrome browser, which I highly recommend.
If you get an error similar to this:Unable to locate the ionic.project file. Are you in your project directory? (CLI v1.6.4)then you didn’t run theionic serve
command in the project directory (as the error clearly says), and so you should firstcd
into that directory (as mentioned in the previous step).
Now, let’s go and see what our generated folder structure looks like and what is each folder responsible for.
Ionic application folder structure
If you open up the project in your editor (I’m using Sublime Text 3 on the image below), you will see something like:
hooks folder
hooks folder contains code for Cordova hooks, which are used to execute some code during the Cordova build process. For example, Ionic uses Cordova’s after_prepare hook to inject platform specific (iOS, Android) CSS and HTML code.
plugins folder
plugins folder contains Cordova plugins which are added to the project. You can addany available Cordova plugin⁵⁶ to your project, and you can even create your own if you’re technical enough. As you can see from the image above we currently have 5 installed plugins (com.ionic.keyboard, console, device, splashscreen, and cordova-plugin-whitelist).
scss folder
scss folder contains the ionic.app.scss file which is based on SASS⁵⁷. This file contains default variables like for example theme colors.
SASS is an extension of CSS which adds additional features like nested rules, variables, mixins, etc. There are few frameworks built with Sass like for example Compass⁵⁸,
Bourbon⁵⁹, andSusy⁶⁰. You can learn more about how to use Sass in theofficial guide⁶¹. You don’t need to use Sass in Ionic if you don’t want to (it’s actually turned off by default), but if you’re familiar with it, you can initialize Ionic to use it with theionic setup sass, and Gulp (more
about it below) will automatically compile the Sass code into CSS.
www folder
www folder is the most important since it contains all the files our application is made of, and we will be spending most of our development time in this folder. This folder contains few files and additional subfolders which we’ll address in more detail in the next section titled Refactoring our application. ⁵⁶http://plugins.cordova.io/#/ ⁵⁷http://sass-lang.com/ ⁵⁸http://compass-style.org/ ⁵⁹http://bourbon.io/ ⁶⁰http://susy.oddbird.net/ ⁶¹http://sass-lang.com/guide
bower.json and .bowerrc files
bower.json is a configuration file forBower⁶².Bower is a package manager for front-end modules that are usually comprised of JavaScript and/or CSS. It lets us easily search for, install, update, or remove these front-end depfront-endencies. If you want to learn more about Bower, you can check out my post
How to Manage Front-End JavaScript and CSS Dependencies with Bower⁶³.
The contents of my bower.json file is shown below (you will see the same content if you cloned the project from Github or started it from my Ionic Creator template): { "name": "HelloIonic", "private": "true", "devDependencies": { "ionic": "driftyco/ionic-bower#1.1.0" } }
Bower stores the downloaded front-end modules in a folder which is defined in a .bowerrc file, and is set to www/lib by default.
The contents of the.bowerrcfile is shown below: { "directory": "www/lib" }
config.xml file
config.xml is a configuration file for the Cordova⁶⁴ project (as you may remeber from the first chapter, Ionic is built on top of Cordova). It contains some meta information about the app like permissions and a list of Cordova plugins which are used in the app. To learn more about available settings in theconfig.xmlfile, please refer to theofficial documentation⁶⁵.
gulpfile.js file
gulpfile.js is a configuration file forGulp⁶⁶.
Gulp is a JavaScript task runner that helps with rapid development by making use of its multiple plugins for different tasks like concatenation, minifying, automatic unit test running, LESS/SASS to CSS compilation, copying modified files to different directories, etc…
Another popular task runner isGrunt⁶⁷. However, from my personal experience I tend to favor Gulp as well.
Note: you don’t need to learn Gulp in order to use Ionic. If, however, you want, you can check out the officialGetting started documentation⁶⁸.
⁶²http://bower.io/ ⁶³ http://www.nikola-breznjak.com/blog/codeproject/how-to-manage-front-end-javascript-and-css-dependencies-with-bower-on-ubuntu-14-04/ ⁶⁴https://cordova.apache.org/ ⁶⁵https://cordova.apache.org/docs/en/4.0.0/config_ref_index.md.html ⁶⁶http://gulpjs.com/ ⁶⁷http://gruntjs.com/ ⁶⁸https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md
ionic.project
ionic.project is a configuration file for Ionic, used to store meta information about Ionic project and the associated Ionic.io cloud account. We’re not going to use Ionic.io cloud account just yet, we’ll show how to use it in the next chapter.
package.json
package.json is a file used by npm to store versions of the npm packages installed in the current
project.
npm(Node.js Package Manager) is a CLI tool which comes with Node.js installation and
it’s used for installing other tools like aftorementioned Bower, Gulp, etc…
Contents of mypackage.jsonfile, shown below, is useful as we can see which Cordova plugins and
dependencies are installed for the project, as well as some meta information like name, version and description:
1 {
2 "name": "ionic_2ndtutorial",
3 "version": "1.0.0",
4 "description": "Ionic_2ndTutorial: An Ionic project",
5 "dependencies": { 6 "gulp": "^3.5.6", 7 "gulp-sass": "^1.3.3", 8 "gulp-concat": "^2.2.0", 9 "gulp-minify-css": "^0.3.0", 10 "gulp-rename": "^1.2.0" 11 }, 12 "devDependencies": { 13 "bower": "^1.3.3", 14 "gulp-util": "^2.2.14", 15 "shelljs": "^0.3.0" 16 }, 17 "cordovaPlugins": [ 18 "cordova-plugin-device", 19 "cordova-plugin-console", 20 "cordova-plugin-whitelist", 21 "cordova-plugin-splashscreen", 22 "com.ionic.keyboard" 23 ], 24 "cordovaPlatforms": [] 25 }
.gitignore and README.md file
Both .gitignore and README.md are files related toGitHub⁶⁹.
I’m sure most of the readers know and use GitHub (and consequentlyGit⁷⁰), but just for brevity, let seehow Wikipedia defines GitHub⁷¹:
GitHub is a Web-based Git repository hosting service, which offers all of the distributed revision control and source code management (SCM) functionality of Git as well as adding its own features. Unlike Git, which is strictly a command-line tool, GitHub provides a Web-based graphical interface and desktop as well as mobile integration. It also provides access control and several collaboration features such as bug tracking, feature requests, task management, and wikis for every project.
So,Git⁷²on the other hand is (quoted from the official site):
a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. Git is easy to learn and has a tiny footprint with lightning fast performance. It outclasses SCM tools like Subversion, CVS, Perforce, and ClearCase with features like cheap local branching, convenient staging areas, and multiple workflows.
Now that we got the basics out of the way, let’s take a look at what the aftorementioned two files represent.
.gitignore is a configuration file for GitHub. Contents of the.gitignorefile, shown below, basically
instructs Git that it should not track folders node_modules, platforms and plugins when uploading the code to GitHub. “‘ # Specifies intentionally untracked files to ignore when using Git # http://git-scm.com/docs/gitignore
node_modules/ platforms/ plugins/ “‘
README.md is aMarkdown⁷³file used on GitHub to explain the purpose and usage of your project. If you’re not using Git (and Github) in your workflow, I highly encourage you to do so, as it will prove really useful in the long run.
⁶⁹https://github.com/ ⁷⁰https://git-scm.com/
⁷¹https://en.wikipedia.org/wiki/GitHub ⁷²https://git-scm.com/
Refactoring our application
As said, we’ll be spending most of our development time in the www folder and that’s why we mentioned it just briefly in the previous section. We’ll take a full deep dive in it here, by taking the two most imporant files (index.html and app.js) and explain their contents step by step.
Also, we’ll refactor our code into separate files, since Ionic Creator put everything in one. Finally, we’ll add the calculator logic so that our calculator will work as expected.
Generally, putting all the code in one file and mixing logic and presentation (JavaScript and HTML code) is simply a big NO-NO, and often referred to asspaghetti code⁷⁴. You can learn more about refactoring your code from the cult bookRefactoring: Improving the Design of Existing Code⁷⁵ by Martin Fowler, Kent Beck, and others. If you’re searching for a bit lighter introduction to refactoring and good programing practices in general I can’t recomment the classicCode Complete 2⁷⁶by Steve McConnell enough.
index.html file
The starting point of our Ionic application isindex.html, whose contents is as follows:
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalab\
6 le=no, width=device-width"> 7 <title></title> 8 9 <style> 10 .angular-google-map-container { 11 width: 100%; 12 height: 504px; 13 } 14 </style> 15
16 <link href="lib/ionic/css/ionic.css" rel="stylesheet">
17 <script src="lib/ionic/js/ionic.bundle.js"></script>
18
19 <link href="http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.c\ ⁷⁴https://en.wikipedia.org/wiki/Spaghetti_code
⁷⁵http://amzn.to/1LWo4Ow ⁷⁶http://amzn.to/1LWomoq
20 ss" rel="stylesheet">
21
22 <!-- IF using Sass (run gulp sass first), then uncomment below and remove th\
23 e CSS includes above
24 <link href="css/ionic.app.css" rel="stylesheet">
25 -->
26
27 <script>
28 // Ionic Starter App
29
30 // angular.module is a global place for creating, registering and retrie\
31 ving Angular modules
32 // 'starter' is the name of this angular module example (also set in a <\
33 body> attribute in index.html)
34 // the 2nd parameter is an array of 'requires'
35 // 'starter.services' is found in services.js
36 // 'starter.controllers' is found in controllers.js
37 angular.module('app', ['ionic'])
38
39 .run(function($ionicPlatform) {
40 $ionicPlatform.ready(function() {
41 // Hide the accessory bar by default (remove this to show the access\
42 ory bar above the keyboard
43 // for form inputs)
44 if(window.cordova && window.cordova.plugins.Keyboard) {
45 cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); 46 } 47 if(window.StatusBar) { 48 // org.apache.cordova.statusbar required 49 StatusBar.styleDefault(); 50 } 51 }); 52 }) 53
54 .config(function($stateProvider, $urlRouterProvider) {
55 // Ionic uses AngularUI Router which uses the concept of states
56 // Learn more here: https://github.com/angular-ui/ui-router
57 // Set up the various states which the app can be in.
58 // Each state's controller can be found in controllers.js
59 $stateProvider
60 .state('page1', {
62 templateUrl: 'page1.html'
63 });
64
65 // if none of the above states are matched, use this as the fallback
66 $urlRouterProvider.otherwise('');
67 });
68 </script>
69 </head>
70
71 <body ng-app="app" animation="slide-left-right-ios7">
72 <div>
73 <div>
74 <ion-nav-bar class="bar-stable">
75 <ion-nav-back-button class="button-icon icon ion-ios7-arrow-back\
76 ">Back</ion-nav-back-button> 77 </ion-nav-bar> 78 79 <ion-nav-view></ion-nav-view> 80 </div> 81 </div> 82
83 <script id="page1.html" type="text/ng-template">
84 <ion-view title="Calculator">
85 <ion-content padding="false" class="has-header">
86 <form>
87 <label class="item item-input" name="display">
88 <span class="input-label">Input</span>
89 <input type="text" placeholder="0" />
90 </label>
91 </form>
92
93 <div class="button-bar">
94 <button class="button button-stable button-block ">7</button>
95 <button class="button button-stable button-block ">8</button>
96 <button class="button button-stable button-block ">9</button>
97 <button class="button button-energized button-block ">/</but\
98 ton>
99 </div>
100 <div class="button-bar">
101 <button class="button button-stable button-block ">4</button>
102 <button class="button button-stable button-block ">5</button>
104 <button class="button button-energized button-block ">x</but\
105 ton>
106 </div>
107 <div class="button-bar">
108 <button class="button button-stable button-block ">1</button>
109 <button class="button button-stable button-block ">2</button>
110 <button class="button button-stable button-block ">3</button>
111 <button class="button button-energized button-block ">-</but\
112 ton>
113 </div>
114 <div class="button-bar">
115 <button class="button button-assertive button-block ">C</but\
116 ton>
117 <button class="button button-stable button-block ">0</button>
118 <button class="button button-positive button-block ">=</butt\
119 on>
120 <button class="button button-energized button-block ">+</but\
121 ton> 122 </div> 123 </ion-content> 124 </ion-view> 125 </script> 126 </body> 127 </html>
Here we’ll go step by step throguh theindex.htmlfile by explaining the needed lines of
code. I’m expecting that you have a decent understanding of HTML so I won’t explain each and every HTML tag. Also, we’ll remove the unnecessary pieces, and move some other parts of the code to different files.
The<meta>element:
1 <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=n\
2 o, width=device-width">
3 ``
4
5 is used to properly resize our application on mobile devices.
6
7 Next, you can safely remove the `<style>` element completely out of the file:
This CSS style is for the map template example, which we don’t have here, so to be completely honest I’m not sure why they included it in this template. I’m guessing that if you’ll be following this book at a later stage this will be removed by the Ionic Creator team.
Since we’re not going to use SASS in this example (we will cover this in the later chapter), we can safely remove the following<link>tag:
1 <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CS\
2 S includes above
3 <link href="css/ionic.app.css" rel="stylesheet">
4 -->
Next, as you can see, there is nowhere a reference to thejs/app.jsfile inside theindex.htmlfile,
thus meaning it’s not used anywhere. If by any chance you’ve looked around the file structure of the application we created in the first chapter you will most likely find this strange. Indeed, Ionic Creator needs some additional tweaking, but I’m sure this will all be dealt with in the future. Since the code inside the<script>element is JavaScript (AngularJS to be more exact) and it’s mixed
with HTML, we don’t want to have that so we’re going to copy the contents of the<script>element
and paste it (by overwriting its whole contents) to the fileapp.js(resides in thejsfolder).
So, ourjs/app.jsfile should now look like this (first few lines of comments are ommited):
1 angular.module('app', ['ionic'])
2 .run(function($ionicPlatform) {
3 $ionicPlatform.ready(function() {
4 // Hide the accessory bar by default (remove this to show the accessory bar \
5 above the keyboard
6 // for form inputs)
7 if(window.cordova && window.cordova.plugins.Keyboard) {
8 cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); 9 } 10 if(window.StatusBar) { 11 // org.apache.cordova.statusbar required 12 StatusBar.styleDefault(); 13 } 14 }); 15 }) 16
17 .config(function($stateProvider, $urlRouterProvider) {
18 // Ionic uses AngularUI Router which uses the concept of states
19 // Learn more here: https://github.com/angular-ui/ui-router
20 // Set up the various states which the app can be in.
22 $stateProvider 23 .state('page1', { 24 url: '', 25 templateUrl: 'page1.html' 26 }); 27
28 // if none of the above states are matched, use this as the fallback
29 $urlRouterProvider.otherwise('');
30 });
Since we removed the contents of the <script>element and pasted it in the js/app.js file, we
need to add a reference to it from theindex.htmlfile, and we can do this by placing the following <script>element just before the ending</head>element:
<script src="js/app.js"></script>
The next important thing is the ng-app directive which is added as an attribute on the<body>tag.
This is just a way to let AngularJS know how tobootstrap the application⁷⁷. Important thing to note is that we have to use the same name inapp.jsfile when we define the root angular module. As
you can see from theapp.jsfile: angular.module('app', ['ionic'])
and from theindex.htmlfile:
<body ng-app="app" animation="slide-left-right-ios7">
in our example this name is simply app.
There’s just one more thing we’re going to do in theindex.html file. See the anotherscript tag
inside our body tag:
<script id="page1.html" type="text/ng-template">
Well, this also looks like a good piece to take out and put into its own file. Again, if you saw the file structure from the application in the first chapter you might remember that the default place to put the template files is inside thetemplatesfolder.
Since we don’t have that folder in our example, let’s create it inside thewwwfolder. Then, create the calculator.htmlfile and paste the contents of the previously mentioned<script>tag. This is how
ourtemplates/calculator.htmlfile should look like now:
1 <ion-view title="Calculator">
2 <ion-content padding="false" class="has-header">
3 <form>
4 <label class="item item-input" name="display">
5 <span class="input-label">Input</span>
6 <input type="text" placeholder="0">
7 </label>
8 </form>
9 <div class="button-bar">
10 <button class="button button-stable button-block ">7</button>
11 <button class="button button-stable button-block ">8</button>
12 <button class="button button-stable button-block ">9</button>
13 <button class="button button-energized button-block ">/</button>
14 </div>
15 <div class="button-bar">
16 <button class="button button-stable button-block ">4</button>
17 <button class="button button-stable button-block ">5</button>
18 <button class="button button-stable button-block ">6</button>
19 <button class="button button-energized button-block ">x</button>
20 </div>
21 <div class="button-bar">
22 <button class="button button-stable button-block ">1</button>
23 <button class="button button-stable button-block ">2</button>
24 <button class="button button-stable button-block ">3</button>
25 <button class="button button-energized button-block ">-</button>
26 </div>
27 <div class="button-bar">
28 <button class="button button-assertive button-block ">C</button>
29 <button class="button button-stable button-block ">0</button>
30 <button class="button button-positive button-block ">=</button>
31 <button class="button button-energized button-block ">+</button>
32 </div>
33 </ion-content>
34 </ion-view>
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalab\
6 le=no, width=device-width">
7 <title></title>
8
9 <link href="lib/ionic/css/ionic.css" rel="stylesheet">
10 <script src="lib/ionic/js/ionic.bundle.js"></script>
11 <link href="http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.c\
12 ss" rel="stylesheet">
13
14 <script src="js/app.js"></script>
15 </head>
16
17 <body ng-app="app" animation="slide-left-right-ios7">
18 <div>
19 <div>
20 <ion-nav-bar class="bar-stable">
21 <ion-nav-back-button class="button-icon icon ion-ios7-arrow-back\
22 ">Back</ion-nav-back-button> 23 </ion-nav-bar> 24 <ion-nav-view></ion-nav-view> 25 </div> 26 </div> 27 </body> 28 </html>
app.js file
Contents of the app.js file bootstraps our Ionic (well, more acurately AngularJS) application, configures necessary plugings, and defines the states in our application. As we said before, the name of the root module matches the value given to theng-appdirective in theindex.htmlfile (app in
our case). Also, we need to inject ‘ionic’ module dependency to our root module so that we can use
the Ionic library directives and other Ionic components.
$ionicPlatform.ready event is triggered after the device (your mobile phone on which the
application is started) is all set up and ready to use. This includes plugins which are used with this project. If you would try to check if some plugin is available outside thereadyfunction callback,
you could get wrong results due to the fact that it is possible that some plugin would not have been set up just yet. Using the aforementioned $ionicPlatform.ready event and placing your code to
check for plugin instantiations solves these issues. You can learn more about ionicPlatform utility methods here:http://ionicframework.com/docs/api/utility/ionic.Platform/⁷⁸.
Inside the $ionicPlatform.ready function’s callback, we’re detecting if a Keyboard plugin is
available in our Ionic application. If so, we’re hiding the keyboard accessory bar (buttons likenext, previousanddone). You can change these settings, and quite a bit of additional ones (see afull list
here⁷⁹), as per your project’s requirements.
As we mentioned before, you can check the list of installed plugins in your package.json file.
But, also, you can check them from your Terminal/Command prompt by executing the following command:
ionic plugin list
In our case, the output should be as follows:
1 com.ionic.keyboard 1.0.4 "Keyboard"
2 cordova-plugin-console 1.0.1 "Console"
3 cordova-plugin-device 1.0.1 "Device"
4 cordova-plugin-splashscreen 2.1.0 "Splashscreen"
5 cordova-plugin-whitelist 1.0.0 "Whitelist"
From the listing above we can see that there is no StatusBar plugin (org.apache.cordova.statusbar), so we can safely remove the corresponding lines in theapp.jsfile.
Inside theconfigfunction callback we’re setting the routes for our application. Ionic usesAngularUI
Router⁸⁰ which uses the concept of states. Since we moved our calculator UI into the calcula-tor.htmlfile inside thetemplatesfolder, we have to adjust the path to it accordingly. Also, we’ll
put our calculator logic inside the so called CalculatorCtrlcontroller. The state definition, with
the acompanying controller definition should now look like this:
1 $stateProvider 2 .state('calculator', { 3 url: '', 4 templateUrl: 'templates/calculator.html', 5 controller: 'CalculatorCtrl' 6 });
Calculator logic with controllers
We will put the code of our CalculatorCtrlinside a new file. So, create a file called Calcula-torCtrl.jsinside thejsfolder. In theindex.htmlput the reference to this new controller file by
adding:
⁷⁸http://ionicframework.com/docs/api/utility/ionic.Platform/ ⁷⁹https://github.com/driftyco/ionic-plugin-keyboard ⁸⁰https://github.com/angular-ui/ui-router