angularjs离子和全局变量:使变量在全球范围内可用的最佳实践

前端之家收集整理的这篇文章主要介绍了angularjs离子和全局变量:使变量在全球范围内可用的最佳实践前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是Angular / Ionic的新手.
在使用Angular / Ionic之前,在我的应用程序启动时,我正在检查我们是否在Phonegap或浏览器下使用并将此信息存储在全局布尔变量中,然后检查应用程序是在线还是离线并将其存储到全局变量也是如此:
  1. var isPhoneGap;
  2. var connectionStatus;
  3. isPhoneGap = checkIfPhoneGap();
  4.  
  5. //later in the code :
  6.  
  7. connectionStatus = checkIfOnline();
  8.  
  9. function checkIfPhoneGap() {
  10. var app = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1; // && document.URL.indexOf( 'file://' );
  11. if ( app ) {
  12. return true;
  13. } else {
  14. return false;
  15. }
  16. }
  17. function checkIfOnline() {
  18. if ( isPhoneGap ) {
  19. if (checkConnection() == "none" ) {
  20. connectionStatus = 'offline';
  21. } else {
  22. connectionStatus = 'online';
  23. }
  24. function checkConnection() {
  25. var networkState = navigator.network.connection.type;
  26. var states = {};
  27. states[Connection.UNKNOWN] = 'Unknown connection';
  28. states[Connection.ETHERNET] = 'Ethernet connection';
  29. states[Connection.WIFI] = 'WiFi connection';
  30. states[Connection.CELL_2G] = 'Cell 2G connection';
  31. states[Connection.CELL_3G] = 'Cell 3G connection';
  32. states[Connection.CELL_4G] = 'Cell 4G connection';
  33. states[Connection.NONE] = 'No network connection';
  34. //console.log('Connection : ' + Connection);
  35. //console.log('Connection type: ' + states[networkState]);
  36. return networkState;
  37. }
  38. } else {
  39. connectionStatus = navigator.onLine ? 'online' : 'offline';
  40. }
  41. return connectionStatus;
  42. }

现在我想对Angular / Ionic做同样的事情,我知道我必须使用“服务”.但这是通过所有代码提供此信息的最佳方式吗?

我正在做以下事情,但这是“最佳做法”吗?

在index.html中:

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

在services.js中:

  1. angular.module('SnowBoard.services',[])
  2.  
  3. .factory('isPhoneGap',function() {
  4.  
  5. var appp = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1; // && document.URL.indexOf( 'file://' );
  6. if ( appp ) {
  7. return true;
  8. } else {
  9. return false;
  10. }
  11.  
  12. })
  13.  
  14. ;

在app.js中:

  1. angular.module('SnowBoard',['ionic','SnowBoard.controllers','SnowBoard.services'])
  2.  
  3. .run(["isPhoneGap","$ionicPlatform",function(isPhoneGap,$ionicPlatform) {
  4. $ionicPlatform.ready(function() {
  5. // Hide the accessory bar by default (remove this to show the accessory bar 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. //CHECK IF ONLINE
  17. connectionStatus = checkIfOnline(isPhoneGap);
  18.  
  19. //DEBUG
  20. //var debugOptionUseLocalDB=0;
  21. //updateProDB(connectionStatus,debugOptionUseLocalDB);
  22. }])
  23. .config(function($stateProvider,$urlRouterProvider) {
  24. //...all state configurations
  25. })
  26. .config(function($stateProvider,$urlRouterProvider) {
  27. //...
  28. });

这适用于现在,但我需要布尔值isPhoneGap在我需要的任何地方都可用(几乎在我的应用程序中的任何地方).

你能收敛到最好的做法吗?

谢谢

您不应该使用$rootScope设置变量,并尽量避免使用$scope.使用LocalStorage是可以的,但这些数据将持续存在.我建议使用SessionStorage设置工厂来存储和检索变量. SessionStorage与您打开的选项卡相关联,因此数据在关闭时消失.

这是我的会话存储服务之一.我抛出$cookie存储以防本地存储不可用.此外,localStorage只能存储字符串.这就是为什么你会看到我根据需要在JSON之间转换对象和数组的原因.注入sessionService之后,我只需调用sessionService.store(name,data)来存储会话变量或sessionService.persist(name,data)来存储持久数据,即如果选中“Remember Me”则存在userName. :

  1. .service('sessionService',['$cookieStore',function ($cookieStore) {
  2. var localStoreAvailable = typeof (Storage) !== "undefined";
  3. this.store = function (name,details) {
  4. if (localStoreAvailable) {
  5. if (angular.isUndefined(details)) {
  6. details = null;
  7. } else if (angular.isObject(details) || angular.isArray(details) || angular.isNumber(+details || details)) {
  8. details = angular.toJson(details);
  9. };
  10. sessionStorage.setItem(name,details);
  11. } else {
  12. $cookieStore.put(name,details);
  13. };
  14. };
  15.  
  16. this.persist = function(name,details) {
  17. if (localStoreAvailable) {
  18. if (angular.isUndefined(details)) {
  19. details = null;
  20. } else if (angular.isObject(details) || angular.isArray(details) || angular.isNumber(+details || details)) {
  21. details = angular.toJson(details);
  22. };
  23. localStorage.setItem(name,details);
  24. }
  25. };
  26.  
  27. this.get = function (name) {
  28. if (localStoreAvailable) {
  29. return getItem(name);
  30. } else {
  31. return $cookieStore.get(name);
  32. }
  33. };
  34.  
  35. this.destroy = function (name) {
  36. if (localStoreAvailable) {
  37. localStorage.removeItem(name);
  38. sessionStorage.removeItem(name);
  39. } else {
  40. $cookieStore.remove(name);
  41. };
  42. };
  43.  
  44. var getItem = function (name) {
  45. var data;
  46. var localData = localStorage.getItem(name);
  47. var sessionData = sessionStorage.getItem(name);
  48.  
  49. if (sessionData) {
  50. data = sessionData;
  51. } else if (localData) {
  52. data = localData;
  53. } else {
  54. return null;
  55. }
  56.  
  57. if (data === '[object Object]') { return null; };
  58. if (!data.length || data === 'null') { return null; };
  59.  
  60. if (data.charAt(0) === "{" || data.charAt(0) === "[" || angular.isNumber(data)) {
  61. return angular.fromJson(data);
  62. };
  63.  
  64. return data;
  65. };
  66.  
  67. return this;
  68. }])

$cookieStore是ngCookies的一部分.确保包含angular-cookies.js并像任何模块一样加载ngCookies. Angular ngCookies

猜你在找的Angularjs相关文章