Edit on March 30, 2015: Please see my follow up here for a few small tweaks: Working with IBM Mobile First and Ionic – a follow up
A few weeks ago I blogged about using hybrid mobile applications and MobileFirst. Today I'm going to demonstrate how to work with Ionic and MobileFirst. What follows is a combination of the steps necessary for bringing any existing Cordova application into MobileFirst along with things necessary for Ionic specifically. As before, credit goes to my coworker Carlos Santana for figuring these steps out. I've also recorded a video of the process you can watch at the end of this blog post.
Create, and Start, your MF Server
To begin, I'm assuming you've got a MobileFirst server up and running already with a hybrid application. If you don't remember how to do that, please read my earlier blog post where I walk you through the commands you have to enter at the command line.I always take baby steps, so once you have your server running, confirm everything is kosher by opening up the console and running your app in the Mobile Browser Simulator.
Set up the Bits
Ok, at the command line, or in Explorer/Finder, move the common folder elsewhere. Remember that the common folder is where your web assets live. You're going to want to copy some bits from this folder so for now don't delete it.Next, grab a copy of Ionic. I'm assuming you've already installed Ionic, but if not, follow the installation instructions. Ionic's CLI will normally create a new project as a Cordova project, but all we want are the web assets. The CLI has a flag for that, --no-cordova. You can create a new application without a full Cordova project like so:
ionic start --no-cordova ioniccode blank
Notice I used the blank template and a folder called ioniccode. Open that folder up and you will see the following assets:
Copy that www folder into the root of your app folder and rename it common. Your app folder should then look something like this:
Again, both my original common folder (common-orig in the screen shot above) and the Ionic folder (ioniccode) can be removed later. As I said, I'm keeping them in so I can copy some bits over.
Update the Code
Ok, now you need to update the code a bit. Your common folder is a copy of the Ionic "Blank" starter, but what I describe here would apply to the other templates as well.
First, we need to make some modifications to the index.html file:
- You need to comment out (or just remove) cordova.js. This is necessary because MobileFirst will inject the script tag automatically.
<!-- <script src="cordova.js"></script> -->
- You need to copy in MobileFirst's jQuery alias.
<script>window.$ = window.jQuery = WLJQ;</script>
- You need to add a new file to include the MobileFirst initialization stuff. Technically you don't need to add a new file, you could modify the existing app.js, but I think it makes sense to break this out into a new file. The default MobileFirst template uses three files, but we can combine them into one. I'm calling mine wlInit.js. MobileFirst used to be called Worklight, and a lot of the code uses "WL" as an acronym, so I used it in my file as well.
<script src="js/wlInit.js"></script>
Here is the completely updated index.html file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script>window.$ = window.jQuery = WLJQ;</script>
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<!--
<script src="cordova.js"></script>
-->
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/wlInit.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content>
</ion-content>
</ion-pane>
</body>
</html>
Next, open up style.css. This is blank (except for a comment) in the Ionic template, but we need to add the following style declaration:
html, body {
height: 100%;
}
This is required because the application ends up with a 0% height when run under MobileFirst. Odd - but just go with it.
Now open app.js. In the run() portion there is code that works with the Ionic keyword plugin. For now, we're going to simply disable it. In a later blog post I'll talk about working with plugins and MobileFirst, but for now, you can safely comment it out.
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
/*
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
*/
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
Ok, so for the last part, we need to create wlInit.js. As I said, this is code that handles initializing MobileFirst stuff. In later blog posts, I'll demonstrate some of those cool features with Ionic, but for now, we're going to keep the file pretty simple. You can copy and paste the contents of initOptions.js and main.js directly into your new file. (And again, this is a personal preference. If you want to keep them in two separate files, that's fine too, just be sure to include them both back in index.html.)
We need to do one more small tweak. When using Ionic and a "regular" Cordova project, there is a hook that applies a style for Android and iOS. We don't have those hooks under MobileFirst, so we have to do it by hand, but that's easy enough. The MobileFirst JavaScript API has a getEnvironment function that returns information about the running environment. We can use that to sniff iPhone and iPad versus Android. (And again, credit for this goes to Carlos.) Here is the entire file with that modification within wlCommonInit.
// Uncomment the initialization options as required. For advanced initialization options please refer to IBM MobileFirst Platform Foundation Knowledge Center
var wlInitOptions = {
// # To disable automatic hiding of the splash screen uncomment this property and use WL.App.hideSplashScreen() API
//autoHideSplash: false,
// # The callback function to invoke in case application fails to connect to MobileFirst Server
//onConnectionFailure: function (){},
// # MobileFirst Server connection timeout
//timeout: 30000,
// # How often heartbeat request will be sent to MobileFirst Server
//heartBeatIntervalInSecs: 20 * 60,
// # Enable FIPS 140-2 for data-in-motion (network) and data-at-rest (JSONStore) on iOS or Android.
// Requires the FIPS 140-2 optional feature to be enabled also.
//enableFIPS : false,
// # The options of busy indicator used during application start up
//busyOptions: {text: "Loading..."}
};
if (window.addEventListener) {
window.addEventListener('load', function() { WL.Client.init(wlInitOptions); }, false);
} else if (window.attachEvent) {
window.attachEvent('onload', function() { WL.Client.init(wlInitOptions); });
}
function wlCommonInit(){
/*
* Use of WL.Client.connect() API before any connectivity to a MobileFirst Server is required.
* This API should be called only once, before any other WL.Client methods that communicate with the MobileFirst Server.
* Don't forget to specify and implement onSuccess and onFailure callback functions for WL.Client.connect(), e.g:
*
* WL.Client.connect({
* onSuccess: onConnectSuccess,
* onFailure: onConnectFailure
* });
*
*/
// Common initialization code goes here
var env = WL.Client.getEnvironment();
if(env === WL.Environment.IPHONE || env === WL.Environment.IPAD){
document.body.classList.add('platform-ios');
} else if(env === WL.Environment.ANDROID){
document.body.classList.add('platform-android');
}
}
And that's it. Once you build/deploy (and don't forget you can do that with mfp bd
), you should then see your MobileFirst application using the awesome power of Ionic!
I've attached my copy of the common folder to this blog entry. Also, Carlos created a GitHub repo with modified versions of all the Ionic templates here: https://github.com/csantanapr/mfp-ionic-templates.
Finally, you can watch a video of this entire process here. Sit back and enjoy the silky sounds of my caffeine-fueled voice.
Archived Comments
Nice intro! Hopefully we'll make working with MobileFirst and other Cordova environments much easier down the road. Looking forward to more blog entries of this sort!
Will be demonstrating the WL Logging stuff later today (probably in about 3 hours ish).
Ray, In the sample commands you show -- "cordova start --no-cordova ioniccode blank". It should be "ionic start ..."
Oops. That was a test. You passed.
Fixed.
Nice approach to this. I did a little different from what you did. I simply bootstrapped Angular on my wlCommomIni function inside main.js. With this you don't need to manually add the classes for the environments. Here's the code:
function wlCommonInit() {
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
}
Yeah, I think that's how Carlos handles it too.
so how, and should, I you use the gulpfile, i want it to do automated testing? how do I install things with bower?, these things are in the ioniccode folder
Bower still works to install JS libraries. The Gulp file - I believe - handles SASS? If so, that still works. You just need to make sure you bd (build / deploy) when you are done editing.
But wont bower and gulp both run on the files in the ionic code folder? Not on the files im developing with in the common folder i created
bower should work anywhere afaik. I don't use it myself. The gulp script I don't know about it. Did you try it?
Thanks! Nice post! It worked also for MFP 7.1. :)
It will work - but 7.1 makes things easier. I should have a post on this Monday or Wednesday.
I am using angular-js and ionic framework to built my project in MFP , but i am unable to add cordova-plugins into it ( I cannot add email plugins ) , kindly please help me with these issue.
Share the command you used to add the plugin and the error you got.
https://developer.ibm.com/m... i followed these link but i could not add plugins to my app
So when you did the add, what did you see? You said it isn't working, but did you get an error? If you type "cordova plugins ls", what does it report?
Ionic2 ?
I've only begun to touch Ionic2 so I've not done anything with it and MFP.
Hi , i am trying to integrate ionic app with mobile first platform 8.0.0 beta version. In there i am not able get the real device information in the server console. Kindly pls help me with these issue.
I haven't used MF 8 yet and I'm no longer on the MobileFirst dev rel team. I'll ping my buddy to try to help out here.
ok thank you
Hi Raymond, did u get any idea regarding MF 8
I pinged em - give em time. :)
In mfp 8 there is a new CLI mfpdev and a new console to register apps
Check out this video demo I did with ionic and mfp8 see if it can help https://www.youtube.com/wat...
Hi Raymond,
Do you have any idea regarding mobile first 7.1 version connectivity with Ionic App?
"connectivity"?
yes
I don't understand what you are asking though. If you just mean MF + Ionic, that's what this entire post is about.
Exactly...I am using mobile first 7.1V. My Sample,
https://github.com/Smohanap...
Here i am using WL.client.connect() method for connect with the server. In my app , i am not able to get the result either success/failure using this method.
Can you give me your suggestion for this issue?
Do you see an error in your dev tools console?
Hi,
I before i was run my app using Device. I am not able to see any error in my console.
Later, I have tried using the command "mfp preview" in console.In there i am getting the following error,
Error: error code: 304
Error: There was an error building the application.
Error: : Error building .wlapp file
Error details: VError: Error building wlapp file.
VError: Error: Deployment.data contents were null.
Error: Push has failed
Yeah - sorry - not sure what that could be. Carlos Santana - any idea?
ok.Can you tell the configuration of mobile first 7.1,
1) cordova
2)android
3)node
ok.can you tell the requirement for mobile first 7.1 version for,
Android
cordova
Hi, i have a question. I set everything up like in your article. I am trying to invoke now a procedure inside a Angular-Controller with the command WL.Client.invokeProcedure(...). But I get the following error: ReferenceError: WL is not defined.
Can you please help me solving this issue.
Best regards
If you mean setup, then I'd suggest reading the docs. If you don't mean that... then I don't know what you mean.
yes regarding setup only
Then I'd suggest doing what I mentioned - following the documentation first and then reporting back on what went wrong. I don't work with MF anymore so I may not be the best person to help. You can also try StackOverflow.
Hi Raymond, I have created my ionic app & i am trying to integrate it with mobile first 7.1version. can you tell me how to add mfp plugin in 7.1version?
Did you try adding it via the CLI?
Hi Raymod, Thanks for the wonderful intro to Ionic with Worklight.
Sample was deployed successfully but in preview its showing an error of "ionic.bundle.js:13440 Uncaught Error: [$injector:modulerr] Failed to instantiate module ng due to:
TypeError: Cannot set property 'aHrefSanitizationWhitelist' of null
at $$SanitizeUriProvider "
I am not sure whether it is related to angular or worklight. I am using worklight 7.1 and ionic 2.0. Please help me on this.
I tried with altering the loading sequence of worklight and ionic but it did not worked.
with Ionic version 1.7.15 too I am facing the same issue. Please help me.
Sorry - I haven't tried Ionic 2 with MFP. I'm no longer working with MF, but I'll ask Carlos Santana to see if he can help.
Even with Ionic 1.7 I am having the same error.
I heard my name :-) or are you talking about the guitarist?
Hi Durga
From the error messages it smells like the error in coming from angular.
I recommend starting with an empty app start making changes to see where the problem is.
I highly recommend to take a look at the MF Dev center we have labs with ionic samples and videos that take you step by step on how to create your app. https://mobilefirstplatform...
Either will do. :)
Thanks for the reply Carlos. I will try to follow it.May I know which version of ionic is most compatible with worklight 7.1 ?
MobileFirst provides vanilla JavaScript API meaning that the answer is any JavaScript library is compatible
Here you have a sample https://github.com/mfpdev/m...
https://github.com/mfpdev/m...
Why not use MFP8?
You right, but there are users which ask this sample. With 8.0 it is much easier and personally I think it is better approach
Requested from a customer
Can anyone tell me how to add wlapp file manually into mfp 7.1 console without using mfp push command