Angularjs Ionic and Global Variables: Best Practices to Make an Accessible Variable Globally

I am new to Angular / Ionic. Before using Angular / Ionic, when starting my application, I checked if we were in Phonegap or a browser, using and storing this information in a global logical variable, and then checking whether this application was online or offline, and saving its global variable, eg:

var isPhoneGap; var connectionStatus; isPhoneGap = checkIfPhoneGap(); //later in the code : connectionStatus = checkIfOnline(); function checkIfPhoneGap() { var app = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1; // && document.URL.indexOf( 'file://' ); if ( app ) { return true; } else { return false; } } function checkIfOnline() { if ( isPhoneGap ) { if (checkConnection() == "none" ) { connectionStatus = 'offline'; } else { connectionStatus = 'online'; } function checkConnection() { var networkState = navigator.network.connection.type; var states = {}; states[Connection.UNKNOWN] = 'Unknown connection'; states[Connection.ETHERNET] = 'Ethernet connection'; states[Connection.WIFI] = 'WiFi connection'; states[Connection.CELL_2G] = 'Cell 2G connection'; states[Connection.CELL_3G] = 'Cell 3G connection'; states[Connection.CELL_4G] = 'Cell 4G connection'; states[Connection.NONE] = 'No network connection'; //console.log('Connection : ' + Connection); //console.log('Connection type: ' + states[networkState]); return networkState; } } else { connectionStatus = navigator.onLine ? 'online' : 'offline'; } return connectionStatus; } 

Now I would like to do the same with Angular / Ionic, I understand that I need to use the "Service". But the best way to make this information available through all the code?

I am doing the following, but is it "best practice"?

in index.html:

 <script src="js/app.js"></script> <script src="js/controllers.js"></script> <script src="js/services.js"></script> 

in services.js:

 angular.module('SnowBoard.services', []) .factory('isPhoneGap', function() { var appp = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1; // && document.URL.indexOf( 'file://' ); if ( appp ) { return true; } else { return false; } }) ; 

in app.js:

 angular.module('SnowBoard', ['ionic', 'SnowBoard.controllers', 'SnowBoard.services']) .run(["isPhoneGap","$ionicPlatform", function(isPhoneGap, $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) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } }); //CHECK IF ONLINE connectionStatus = checkIfOnline(isPhoneGap); //DEBUG //var debugOptionUseLocalDB=0; //updateProDB(connectionStatus, debugOptionUseLocalDB); }]) .config(function($stateProvider, $urlRouterProvider) { //...all state configurations }) .config(function($stateProvider, $urlRouterProvider) { //... }); 

Now it works, but I need the boolean isPhoneGap be available wherever I need it (almost everywhere in my application).

Can you converge on best practice for this?

thanks

+8
angularjs ionic-framework
source share
3 answers

You should not set variables using $rootScope , and try to refrain from using $scope as much as possible. Using LocalStorage is fine, but this data will be saved. I would recommend SessionStorage up a factory to store and retrieve variables using SessionStorage . SessionStorage tied to an open tab, so data disappears when it is closed.

This is one of my session storage services. I throw $cookieStorage if local storage is not available. In addition, localStorage can only store strings. This is why you will see how I convert objects and arrays to and from JSON as needed. After entering sessionService I only need to call sessionService.store(name, data) to store the session variable or sessionService.persist(name, data) to store persistent data, that is, userName if the Remember Me checkbox is checked.

 .service('sessionService', ['$cookieStore', function ($cookieStore) { var localStoreAvailable = typeof (Storage) !== "undefined"; this.store = function (name, details) { if (localStoreAvailable) { if (angular.isUndefined(details)) { details = null; } else if (angular.isObject(details) || angular.isArray(details) || angular.isNumber(+details || details)) { details = angular.toJson(details); }; sessionStorage.setItem(name, details); } else { $cookieStore.put(name, details); }; }; this.persist = function(name, details) { if (localStoreAvailable) { if (angular.isUndefined(details)) { details = null; } else if (angular.isObject(details) || angular.isArray(details) || angular.isNumber(+details || details)) { details = angular.toJson(details); }; localStorage.setItem(name, details); } else { $cookieStore.put(name, details); } }; this.get = function (name) { if (localStoreAvailable) { return getItem(name); } else { return $cookieStore.get(name); } }; this.destroy = function (name) { if (localStoreAvailable) { localStorage.removeItem(name); sessionStorage.removeItem(name); } else { $cookieStore.remove(name); }; }; var getItem = function (name) { var data; var localData = localStorage.getItem(name); var sessionData = sessionStorage.getItem(name); if (sessionData) { data = sessionData; } else if (localData) { data = localData; } else { return null; } if (data === '[object Object]') { return null; }; if (!data.length || data === 'null') { return null; }; if (data.charAt(0) === "{" || data.charAt(0) === "[" || angular.isNumber(data)) { return angular.fromJson(data); }; return data; }; return this; }]) 

$ cookieStore is part of ngCookies. Make sure you turn on angular-cookies.js and load ngCookies like any module. Angular ngCookies

+10
source share

Firstly, I'm pretty new to both Ionic and Angular, however, I had the same problem with my Angular web application, and I did the following to get it working

  • Assign $rootScope variables so they are visible to all controllers

  • Assign $scope variables that are visible to the current context. Example: controller and html pages use this controller

  • localStorageService because it will hold values ​​even after the user refreshes the page.

Please note again that this is what I have done in my Angular web application and may not be the best practices, but I hope you understand this idea.

+3
source share

In ionic.Platform, methods are available to help return the data you need regarding the type of device.

http://ionicframework.com/docs/api/utility/ionic.Platform/

You can also look at the ngCordova add-on, which has a bunch of useful wrappers around cordova plugins, including the device plugin.

http://ngcordova.com/docs/#Device

0
source share

All Articles