I am new to Ionic an wanted to create an app to send push notifications. I want to start with ANdroid. These are the commands I have used to setup my project:
ionic plugin add https://github.com/phonegap-build/PushPlugin.git
ionic add ngCordova
ionic add ionic-service-core
ionic add ionic-platform-web-client
ionic add angular-websocket
Here is my app.js:
angular.module('starter', ['ionic',
'ngCordova',
'ionic.service.core'])
.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();
}
});
})
.config(['$ionicAppProvider', function($ionicAppProvider) {
$ionicAppProvider.identify({
app_id: 'xx',
api_key: 'xx'
});
}])
.controller('PushCtrl', function($scope, $rootScope, $ionicUser) {
$rootScope.$on('$cordovaPush:tokenReceived', function(event, data) {
//alert("Successfully registered token " + data.token);
alert('Ionic Push: Got token ', data.token, data.platform);
$scope.token = data.token;
});
$scope.identifyUser = function() {
var user = $ionicUser.get();
if(!user.user_id) {
// Set your user_id here, or generate a random one.
user.user_id = $ionicUser.generateGUID();
};
// Metadata
angular.extend(user, {
name: 'Martijn',
});
// Identify your user with the Ionic User Service
$ionicUser.identify(user).then(function(){
$scope.identified = true;
alert('Identified user ' + user.name + '\n ID ' + user.user_id);
});
};
// Registers a device for push notifications
$scope.pushRegister = function() {
alert('Ionic Push: Registering user');
var user = $ionicUser.get();
alert("User Id:" + user.user_id);
Ionic.io();
var push = new Ionic.Push();
var callback = function(data) {
alert('Registered token:', data.token);
//console.log(data.token);
push.addTokenToUser(user);
user.save();
}
push.register(callback); // ERROR
};
});
Index.html:
<!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">
<!-- 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>
<script src="lib/ionic-platform-web-client/dist/ionic.io.bundle.min.js"></script>
<script src="lib/angular-websocket/angular-websocket.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="lib/ionic-service-core/ionic-core.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<!-- Cordova is bootstrapped by ionic-platform-web-client, uncomment this if you remove ionic-platform-web-client... -->
<!-- <script src="cordova.js"></script> -->
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script></head>
<body ng-app="starter" ng-controller="PushCtrl">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content>
<button class="button button-block button-dark" ng-click="identifyUser()">
Identify a user
</button>
<button class="button button-block button-positive" ng-if="identified" ng-click="pushRegister()">
Register for Push
</button>
</ion-content>
</ion-pane>
</body>
</html>
When running this code I can see the User in my Ionic dashboard. But when I hit the Register for push button, I get an exception: ReferenceError: PushNotification is not defined and then it points to /lib/ionic-platform-web-client/dist/ionic.io.bundle.min.js:3:873.
What do I have to do to make this work?
You need to use new tutorial, libraries you have installed are deprecated.
Notifications are not shown in development version, just callback is called.
When setting Android production push notifications up, you need to use GCM project number, not project ID or API key.
Related
1) Added inappbrowser plugins
2) added googleplus plugins
3) installed ngcordova
4) install ng-cordova-oauth
angular.module('starter', ['ionic','ngCordova','ngCordovaOauth'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.controller('WelcomeCtrl', function($scope, $state, UserService, $ionicLoading,$cordovaOauth) {
$scope.googleSignIn = function() {
console.log('In My Method');
$cordovaOauth.google("here i am using my client id", ["https://www.googleapis.com/auth/urlshortener", "https://www.googleapis.com/auth/userinfo.email"]).then(function(result) {
console.log(JSON.stringify(result));
}, function(error) {
console.log('In Error');
console.log(error);
});
};
})
.service('UserService', function() {
var setUser = function(user_data) {
window.localStorage.starter_google_user = JSON.stringify(user_data);
};
var getUser = function(){
return JSON.parse(window.localStorage.starter_google_user || '{}');
};
return {
getUser: getUser,
setUser: setUser
};
});
<!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 rel="manifest" href="manifest.json">
<!-- un-comment this code to enable service worker
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js')
.then(() => console.log('service worker installed'))
.catch(err => console.log('Error', err));
}
</script>-->
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- 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>
<script src="js/ng-cordova.js"></script>
<script src="js/ng-cordova-oauth.min.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>
</head>
<body ng-app="starter" ng-controller="WelcomeCtrl">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content>
<a class="google-sign-in button button-block" ng-click="googleSignIn()">Sign in with Google</a>
</ion-content>
</ion-pane>
</body>
</html>
This code is for login by google in ionic app. but after this, i got a issue "Google no longer supports authentication requests from the web view. More information can be found at https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html.'
Please help me to solve this issue
Unfortunately, you have chosen to implement a soon-to-be-deprecated authentication mechanism for Google. Apr. 2017 is what I believe is the deprecation date, after which this method will not work, and it currently does not work for newer clients.
You will have to implement Google Auth login using the mechanism suggested at that website. Or you can use one of the plugins available, like onymos access.
YES ,Google no longer supports authentication requests from the web view
Just try to make use of Native Oauth Process ,
Please See the link for better understanding
https://www.joshmorony.com/implementing-google-plus-sign-in-with-oauth-2-0-in-ionic-2/
I am developing pusher application by using ionic framework and pusher realtime technologies. 'pusher-angular' dependency injection in app.js is not work in ionic application when I run it in android application. Any suggestion how to solved it? I want to enable $pusher dependency injection in controller so that I can use Pusher realtime API in my application. Any suggestion?
index.html
<!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>
<!-- compiled css output -->
<link href="css/ionic.app.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="//js.pusher.com/3.2/pusher.min.js"></script>
<script src="//cdn.jsdelivr.net/angular.pusher/latest/pusher-angular.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter" >
<ion-nav-view></ion-nav-view>
</body>
</html>
app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
db = window.openDatabase("chatChannel.db", "1", "Demo SQLite Test", "2000");
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS chat_channel(id interger primary key, chat_room text, last_text text, username text, chat_channel text unique)")
});
})
Controller.js
.controller('ChatRoomCtrl', ['$scope', '$state', '$rootScope', '$ionicScrollDelegate',
function($scope, $state, $rootScope,$ionicScrollDelegate){
var client = new Pusher('ed05a79be9c11b452872', {
cluster: 'ap1',
encrypted: true
});
var my_channel = client.subscribe(subscribeChannel);
my_channel.bind('chat_message', function(data) {
console.log(data);
$scope.messages.push(data);
});
}
The first issue I see is with the index.html.
<script src="//js.pusher.com/3.2/pusher.min.js"></script>
<script src="//cdn.jsdelivr.net/angular.pusher/latest/pusher-angular.min.js"></script>
This lines wont work in Android application but will work in browser. It is because android files are loaded from file:// so it will try to load file://js.pusher.com/3.2/pusher.min.js for example.
You will need to precise the protocol like this :
<script src="https://js.pusher.com/3.2/pusher.min.js"></script>
<script src="https://cdn.jsdelivr.net/angular.pusher/latest/pusher-angular.min.js"></script>
This is geo js file which id directly connected via index.html can you please explain me why i am unable to run. whether it is debugging problem or apk extraction problem.
my ionic project works fine with ionic serve --lab ,but while copied the.apk file in build folder to my phone and install the app but blank screen appears ,
Please can anyone suggest what might be my problem
my app is using google maps,key is provieded for both app and browser in index.html
here is my code:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 17.3850, lng: 78.4867},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
//var posOptions={timeout:10000, enableHighAccuracy:true};
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Here');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
<!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">
<!-- 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>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAJWfIcxV1Q1-lG66bpqhLfBB1zevi9bG4&callback=initMap">
</script>
<!-- your app's js -->
<script src="js/geo.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-royal">
<h1 class="title">Geo Location example</h1>
</ion-header-bar>
<ion-content>
<div id="map"></div>
</ion-content>
</ion-pane>
</body>
</html>
I need to wrap a URL inside the ionic application. I test with windows 8, inside chrome broswer.
On Windows Chrome: redirect to the page inside browser
On Android Phone: close the application without any warning or something else in console.
Please give me a solution to what I need without using iframes.
I followed all the info that each docs gave me and this is how I implement it:
app.js file:
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic', 'ngCordova'])
.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();
}
});
})
.controller('CheckController', function($scope, $cordovaInAppBrowser) {
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener("deviceready", onDeviceReady, false);
} else {
onDeviceReady();
}
function onDeviceReady() {
window.open = $cordovaInAppBrowser.open('http://apache.org', '_self', {
location: 'no',
hidden: 'yes'
}).then(function(event) {
alert('success');
})
.catch(function(event) {
console.log(event);
});
}
});
<!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">
<!-- 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="lib/ngCordova/dist/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Lunch External App Demo</h1>
</ion-header-bar>
<ion-content ng-controller="CheckController">
<div id="map" data-tap-disabled="true"></div>
</ion-content>
</ion-pane>
</body>
</html>
This is working on Android:
ionic.Platform.ready(function(){
// will execute when device is ready, or immediately if the device is already ready.
onDeviceReady3();
});
function onDeviceReady3(){
var options = {
location: 'no',
clearcache: 'no',
toolbar: 'yes', //only for IOS
hidden:'yes'
};
$cordovaInAppBrowser.open('http://google.com', '_self', options)
.then(function(event) {
// success
alert("success");
})
.catch(function(event) {
// error
alert("error");
});
$cordovaInAppBrowser.close();
}
I have followed this article:
to get network information of the device in ionic app for android.
It works fine on browser but when I install the compiled apk in android phone, it gives an error that says Reference error : Connection is not defined. at line where I use $cordovaNetwork.isOnline();
I have been banging my head around and have done my due research and tried uninstalling and installing it in the order suggested but no help.
Help me fix this issue. This problem is probably not an issue with code and may be need some clever fix to get it working.
This same issue is being discussed here but I have not really understood where is that given piece of code coming from.
index.html :
<!DOCTYPE html>
<html ng-app="starter" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<!-- <link href="lib/ionic/css/angular-datepicker.min.css" rel="stylesheet"> -->
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- angular date picker css-->
<link href="lib/datePicker/css/angular-pickadate.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/highcharts-ng.js"></script>
<script src="lib/ionic/js/jquery.min.js"></script>
<script src="lib/ionic/js/highcharts.js"></script>
<script src="lib/ionic/js/ngStorage.min.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.min.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/controllers.js"></script>
</head>
<body ng-controller="LoginCtrl">
<ion-nav-bar class="mob-bar-balanced">
<!-- <ion-nav-back-button>
</ion-nav-back-button> -->
</ion-nav-bar>
<ion-nav-view></ion-nav-view>
</body>
</html>
app.js:
app.factory('ConnectivityMonitor', ['$rootScope', '$cordovaNetwork', function($rootScope, $cordovaNetwork){
return {
isOnline: function(){
if(ionic.Platform.isWebView()){
$rootScope.online = $cordovaNetwork.isOnline();
return $cordovaNetwork.isOnline();
} else {
$rootScope.online = navigator.onLine;
return navigator.onLine;
}
},
isOffline: function(){
if(ionic.Platform.isWebView()){
$rootScope.online = $cordovaNetwork.isOnline();
return !$cordovaNetwork.isOnline();
} else {
$rootScope.online = navigator.onLine;
return !navigator.onLine;
}
},
startWatching: function(){
if(ionic.Platform.isWebView()){
$rootScope.$on('$cordovaNetwork:online', function(event, networkState){
$rootScope.online =true;
console.log("went online");
});
$rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
$rootScope.online =false;
console.log("went offline");
});
}
else {
window.addEventListener("online", function(e) {
$rootScope.online =true;
console.log("went online");
}, false);
window.addEventListener("offline", function(e) {
$rootScope.online =false;
console.log("went offline");
}, false);
}
}
}
}]);
.config(function($stateProvider,$urlRouterProvider){
$stateProvider
.state('Login',{
url:'/login',
onEnter:["$state","$localStorage", '$rootScope' , '$ionicViewSwitcher',function($state,$localStorage, $rootScope, $ionicViewSwitcher){
if((typeof($localStorage.userInfo)!== 'undefined') && (Object.keys($localStorage.userInfo).length !== 0)) {
$ionicViewSwitcher.nextTransition('none');
$state.go("Deployment");
}
}],
templateUrl:'templates/login.html',
controller:'LoginCtrl',
resolve: {
online: function(ConnectivityMonitor){
return ConnectivityMonitor.isOnline();
}
}
})
I don't know about the tutorial you're mentioning, however, you may want to check the post I wrote which goes literally step by step telling you where and why you should put some piece of code (may be useful if you're just starting with Ionic): http://www.nikola-breznjak.com/blog/codeproject/check-network-information-change-with-ionic-famework/.
Also, I made the example code available freely on Github: https://github.com/Hitman666/IonicNetworkInfo. You can download the project (if you don't want to go through the steps yourself) build it for your device and test it on the device.
Here are the steps from the blog posts:
Start a new Ionic project by doing:
ionic start IonicNetworkInfo blank
Then, change the directory to the newly created IonicNetworkInfo:
cd IonicNetworkInfo
Install ngCordova with Bower:
bower install ngCordova
If by some chance you don’t have bower installed, you can install it with npm:
npm install bower -g
Open up the www/index.html file in your favorite editor, and add the reference to ngCordova (just above the cordova.js script):
<!-- This is what you should add, the cordova below you'll already have -->
<script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
Install the ngCordova network plugin by executing the following command in your Terminal/Command prompt (you should do this from the root directory of your app; so, in our case the IonicNetworkInfo directory):
cordova plugin add org.apache.cordova.network-information
To check if you have successfully installed the plugin, you can run the following command (from the root directory – I won’t be repeating this anymore; when I say you should run some command from the Terminal/Command prompt that, in this case, means from the root directory of the application):
cordova plugin list
You should see the following output:
> cordova plugin list
com.ionic.keyboard 1.0.4 "Keyboard"
org.apache.cordova.network-information 0.2.15 "Network Information"
Open up the www/js/app.js file and add ngCordova to the dependencies list, so that basically the first line looks like this:
angular.module('starter', ['ionic', 'ngCordova'])
Create a new controller in the www/js/app.js file called MyCtrl, with the following content:
.controller('MyCtrl', function($scope, $cordovaNetwork, $rootScope) {
document.addEventListener("deviceready", function () {
$scope.network = $cordovaNetwork.getNetwork();
$scope.isOnline = $cordovaNetwork.isOnline();
$scope.$apply();
// listen for Online event
$rootScope.$on('$cordovaNetwork:online', function(event, networkState){
$scope.isOnline = true;
$scope.network = $cordovaNetwork.getNetwork();
$scope.$apply();
})
// listen for Offline event
$rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
console.log("got offline");
$scope.isOnline = false;
$scope.network = $cordovaNetwork.getNetwork();
$scope.$apply();
})
}, false);
})
In this controller you attach an event listener on the deviceready event (because it could be that the device would not have been yet initialized when this code runs) and you get the network information with:
$cordovaNetwork.getNetwork();
The information, about weather you’re connected to the internet is obtained with the following line:
$scope.isOnline = $cordovaNetwork.isOnline();
Then, you register two events $cordovaNetwork:online and $cordovaNetwork:online which trigger when the device gets online/offline. In them you then just update the $scope variables ().
Just for reference, the whole content of the www/js/app.js file should be:
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $cordovaNetwork, $rootScope) {
$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();
}
});
})
.controller('MyCtrl', function($scope, $cordovaNetwork, $rootScope) {
document.addEventListener("deviceready", function () {
$scope.network = $cordovaNetwork.getNetwork();
$scope.isOnline = $cordovaNetwork.isOnline();
$scope.$apply();
// listen for Online event
$rootScope.$on('$cordovaNetwork:online', function(event, networkState){
$scope.isOnline = true;
$scope.network = $cordovaNetwork.getNetwork();
$scope.$apply();
})
// listen for Offline event
$rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
console.log("got offline");
$scope.isOnline = false;
$scope.network = $cordovaNetwork.getNetwork();
$scope.$apply();
})
}, false);
});
In the index.html file, inside the ion-content tag paste the following content:
<div class="card">
<div class="item item-text-wrap">
<h1>Network: {{network}}</h1>
</div>
</div>
<div class="card">
<div class="item item-text-wrap">
<ion-toggle ng-model="isOnline" ng-checked="item.checked">
<h1 ng-show="isOnline">I'm online</h1>
<h1 ng-show="! isOnline">I'm offline</h1>
</ion-toggle>
</div>
</div>
Basically what we do here is we show the contents of the network variable (which is attached to the $scope via the controller). Also, by using the ion-toggle component we show the “I’m online” / “I’m offline” notifications.
Just for reference, the content of the whole index.html file should look like this:
<!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">
<!-- 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>
<script src="lib/ngCordova/dist/ng-cordova.min.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>
</head>
<body ng-app="starter" ng-controller="MyCtrl">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content padding="true">
<div class="card">
<div class="item item-text-wrap">
<h1>Network: {{network}}</h1>
</div>
</div>
<div class="card">
<div class="item item-text-wrap">
<ion-toggle ng-model="isOnline" ng-checked="item.checked">
<h1 ng-show="isOnline">I'm online</h1>
<h1 ng-show="! isOnline">I'm offline</h1>
</ion-toggle>
</div>
</div>
</ion-content>
</ion-pane>
</body>
</html>
In order to test this application you should run it on your device (because you can’t disable network in iOS simulator). If you have an Android device plugged to your computer (and all the SDKs in place) you can run the following to commands to get your application running on your Android device:
ionic build android && ionic run android
Maybe you have not installed Network-Plugin. Please check this.
Now, I think it would be a better approach to use
$ionicPlatform.ready(function() {
$scope.network = $cordovaNetwork.getNetwork();
$scope.isOnline = $cordovaNetwork.isOnline();
$scope.$apply();
});
instead of document.addEventListener("deviceready", function () {