2015-07-20 78 views
0

我有以下代码来在线/离线检查我的cordova应用程序。Cordova角度离线检查

var networkState = navigator.connection.type; 

var states = {}; 
states[Connection.UNKNOWN] = 'Unknown'; 
states[Connection.ETHERNET] = 'Ethernet'; 
states[Connection.WIFI]  = 'WiFi'; 
states[Connection.CELL_2G] = 'Cell2G'; 
states[Connection.CELL_3G] = 'Cell3G'; 
states[Connection.CELL_4G] = 'Cell4G'; 
states[Connection.CELL]  = 'Cellgeneric'; 
states[Connection.NONE]  = 'Nonetwork'; 
alert(states[networkState]); 
if(states[networkState]!='Nonetwork'){ 
online=true; 
}else{ 
online=false; 
} 

而我的角度控制器就像下面。

.controller('MainCtrl',['$scope','$http','$localStorage','$state',function($scope, $http, $localStorage, $state){ 


    if(online==true){ 

    //code for online 
    }else{ 
    // code for offline 
    } 


}]) 

我叫“deviceready”事件的检查,状态得到。但我的问题是 - deviceready被称为后我控制器started.is可以检查网络状态前角控制器开始执行的?

+0

在你的例子中,我看不到'deviceready'被调用的地方。可能会有一些元素缺失。你在哪里叫第一块代码检查网络? – sebastienbarbier

回答

0

在Angular中,控制器在您的应用程序的运行阶段的期间执行。您可以在该运行阶段之前执行一些代码,也称为配置阶段

你应该从角度阅读module documentation

  • 配置块 - 在供应商登记和配置阶段得到执行。只有提供者和常量 可以注入到配置块中。这是为了防止 在完全配置完成 之前意外实例化服务。

  • 运行块 - 在创建注入器后执行并用于启动应用程序。只有实例和常量可以注入到运行块中 。这是为了防止在应用程序运行时进一步配置系统 。

在你的代码,它应该是这样的:如果

angular.module('myModule', []). 
config(function(injectables) { // provider-injector 
    // This is an example of config block. 
    // You can have as many of these as you want. 
    // You can only inject Providers (not instances) 
    // into config blocks. 
}). 
run(function(injectables) { // instance-injector 
    // This is an example of a run block. 
    // You can have as many of these as you want. 
    // You can only inject instances (not Providers) 
    // into run blocks 
}); 

不知道我的理解很好,但是,很可能让你运行你的控制器:)

前执行代码只是想着你的代码...配置将只运行一次,并且你的连接可以随着时间而改变(如果在汽车中,从4G到3G)。所以可能需要检查regularely或检查您的控制器。最好的情况可能是您在控制器激活时调用的函数。