Web and Native Technologies

Ionic Framework

This week I decided to do something very cool! Do you like building android and ios apps, but only know web technologies? No worries, Ionic is here to help. Ionic is a super cool framework that allows you to build cross platform apps without the native language like Objective-c, Swift or Java. Okay, enough of the boring talk. Let’s get down to business. Let’s create our own app!

First thing first we gotta install Node.js. After having downloaded node, we will need to install Cordova and Ionic. Open up your terminal and type

npm install -g cordova ionic

.

Awesome! Now we can start creating our apps. Ionic does a lot of the work for us and lets us choose from three sample templates: Blank, Tabs and a Side menu. For the purpose of this tutorial, we will go with the tabs template.

To create a project, simply follow this recipe ionic start NAME TEMPLATE

ionic start myApp tabs

If you get an error, it’s probably because you will need to be the super user. Just prepend sudo to the previous recipe and you should be good to go.

Now lets cd into our app directory and start up the server.

cd myApp
ionic serve --lab

You should then see some output stating that the server is running, and it should automatically open up the browser for you with the sample app in both an android and ios simulation.

Screen Shot 2015-08-26 at 12.07.16 AM\Screen Shot 2015-08-26 at 12.07.09 AM

Congratulations! You have just created your first ionic app! That wasn’t so hard, now was it? I decided to use the tabs template because it comes with alot of sample content that you can take a look at and experiment with. This is totally awesome for beginners since they can get a feel for how angular and ionic come together. Now we will not be needing a lot of this stuff, so open up the current directory in your favorite text-editor and let’s start deleting some things.

First go to www > templates > tabs.html and delete everything except for the first dashboard tab and add the following:

<!-- About me Tab -->
<ion-tab title="About me" icon-off="ion-ios-person-outline" icon-on="ion-ios-person" href="#/tab/aboutme">
<ion-nav-view name="tab-aboutme"></ion-nav-view>
</ion-tab>

Then change the title of the Dashboard tab to Bio, since we will be changing how this dashboard looks a little later.

Your entire tabs.html should now look like this:


<ion-tabs class="tabs-icon-top tabs-color-active-positive">

<!-- Dashboard Tab -->
<ion-tab title="Bio" icon-off="ion-ios-pulse" icon-on="ion-ios-pulse-strong" href="#/tab/dash">
<ion-nav-view name="tab-dash"></ion-nav-view>
</ion-tab>

<!-- About me Tab -->
<ion-tab title="About me" icon-off="ion-ios-person-outline" icon-on="ion-ios-person" href="#/tab/aboutme">
<ion-nav-view name="tab-aboutme"></ion-nav-view>
</ion-tab>
</ion-tabs>

The <code>ion-tab</code>, is pretty straight-forward. It allows you to create a tab. We then set the title of the tab to “About me” and supply some icons that will be shown when the tab is active or not. We then have an <code>ion-nav-view</code> which basically just renders some templates with it’s own history stack so you can navigate around and it will keep track of your history.

Next go to www > js > app.js. This is where we will be configuring the states of our program. States are basically like routes. It’s a way for the computer to know what page you want rendered when you click on something or go to a specific url. Delete all of the states except for the first two that starts like this: <code>tab</code> and <code>tab.dash</code>. Now add the following state

.state('tab.aboutme', {
url: '/aboutme',
views: {
'tab-aboutme': {
templateUrl: 'templates/tab-aboutme.html',
controller: 'AboutmeCtrl'
}
}
});

Here, we are creating a state tab.aboutme. What this is saying is that it is a child of tab which is why there is a period in between tab and aboutme. The url is simply the url that is mapped to that specific state. When you visit the root of your site and go to root/tab/aboutme.html, it should then load up the controller and the template which we’ve specified in the views

Your entire file should now look like this:


angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);

}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
});
})

.config(function($stateProvider, $urlRouterProvider) {

// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider

// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})

// Each tab has its own nav history stack:

.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl'
}
}
})

.state('tab.aboutme', {
url: '/aboutme',
views: {
'tab-aboutme': {
templateUrl: 'templates/aboutme.html',
controller: 'AboutmeCtrl'
}
}
});

// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/dash');

});

Now, let’s delete the tab-chats.html, tab-account.html and chat-detail.html files and add a new one called aboutme.html. At this point, we should have only three template files.
In your new aboutme.html file, add this:

<ion-view view-title="About me">
  <ion-content>
    <ion-list>
      <ion-item>
        Hi!
    </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

Now let’s go to www > js > controllers.js and delete everything and add

angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope) {})

.controller('AboutmeCtrl', function($scope) {

});

We are not done here yet, but let’s visit services.js which is in the same folder, for just a sec. Here, we will be using a factory. A factory is basically like a blueprint for creating objects. A factory is just an object that returns an object by the result of a function call. This will help us keep our code DRY and easily maintainable.

In this file, delete everything and write the following:

angular.module('starter.services', [])

.factory('MyInfo', function() {

  // Enter your own dummy data here
  var me = {
    name: 'Damian lajara',
    age: 22,
    dob: '05/19/1993',
    school: 'The Flatiron School'
  };

  return {
    info: function() {
      return me;
    }
  };
});

Feel free to enter your own data in the hash instead of just copying mine. This is not really practical, which is why I called it dummy data. It will be better to fetch this data from a JSON file somewhere else and import it into our code, but for the purpose of this tutorial, I decided to stay simple and use a hash.

Now we can go back to our controller file, and use this newly created factory!
Simply inject it into your AboutmeCtrl by passing it as a parameter to the anonymous function.

.controller('AboutmeCtrl', function($scope, MyInfo) {
  $scope.me = MyInfo.info;
});

You may be asking yourself “What is all this $scope I see everywhere”? Well, that is a good question. $scope is a way to interact with the DOM directly without having to touch it. This is done by something called 2-way data binding. Whenever the model is changed, the view will automagically update. So $scope is basically like the bridge between your model and the view. It’s how you can interact with the view and display dynamic data, without having to muck around with the DOM yourself. This is pretty neat since it clearly allows the principle op SOC (separation of concerns) and keeps everything all nice and tidy. The scope is local and only exists within the controller you specify it in. If you remember, in the app.js file, we mapped our controllers to our views within states. This allows us to talk to the view directly through the scope variable inside it’s respective controller.

Now we got all of our controllers and services set up, so let’s revisit our aboutme.html page and add the following:

<ion-view view-title="About me">
  <ion-content>
    <ion-list>
      <ion-item>
        Name: {{me['name']}}
      </ion-item>
      <ion-item>
        Age: {{me['age']}}
      </ion-item>
      <ion-item>
        DOB: {{me['dob']}}
      </ion-item>
      <ion-item>
        School: {{me['school']}}
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

Now let’s add some finishing touches the dashboard. Go to tab-dash.html in the templates directory and add the following:

<ion-view view-title="Dashboard">
  <ion-content class="padding">
<div class="list card">

<div class="item item-avatar">
    <img src="../img/face.jpg">

<h2>{{me['name']}}</h2>

{{me['dob']}}
  </div>

<div class="item item-body">
    <img class="full-image" src="../img/code.png">


      A developer and current student at The Flatiron School who is seeking to gain valuable experience from different fields where my knowledge related to the field of computer science and my skills in programming can contribute to the development of innovative strategies and in the process push my knowledge and skills to it's utmost limits.
    
      <a href="#" class="subdued">1 Like</a>
      <a href="#" class="subdued">5 Comments</a>
    
  </div>

<div class="item tabs tabs-secondary tabs-icon-left">
    <a class="tab-item" href="#">
      <i class="icon ion-thumbsup"></i>
      Like
    </a>
    <a class="tab-item" href="#">
      <i class="icon ion-chatbox"></i>
      Comment
    </a>
    <a class="tab-item" href="#">
      <i class="icon ion-share"></i>
      Share
    </a>
  </div>
</div>

  </ion-content>
</ion-view>

For this part to work, you will have to add two pictures the www > img directory. One profile contact picture and one background picture. I added these pictures already to the img folder under the names of face.jpg and code.png. In order for you to get it working, simply add your two pictures and make sure to replace my name with yours in the tab-dash.html file.

As you can see, I cheated a little and added some code before creating the blueprint for it in the controllers.js file. Here I added {{me['name']}} and {{me['dob']}}, but this will give you an error because name is not within scope of this controller. Let’s go fix this real quick!

Go to your controllers.js file and add simply inject your factory/service which we already created called MyInfo and save it to the $scope variable which will let us bind it to view. Your controllers.js file should now look like this:

angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope, MyInfo) {
  $scope.me = MyInfo.info();
})

.controller('AboutmeCtrl', function($scope, MyInfo) {
  $scope.me = MyInfo.info();
});

You can already see the power of using factories and services here. We were able to share data amongst our controllers without having to actually deal with the data ourselves.

Take a look at the finished output!
Screen Shot 2015-08-26 at 1.45.31 AM

Screen Shot 2015-08-26 at 1.45.40 AM
And that’s it! You have officially created your own ionic app! How easy was that?
You can always view the documentation whenever you want for help, resources and inspiration. I used a lot of the examples in the docs for this tutorial, so if you ever need to go more in depth feel free to experiment on your own. You can also view this up on my Github repo here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s