网络插件ngCodova不适用于控制器

时间:2016-10-22 18:31:27

标签: angularjs cordova ionic-framework ngcordova

我正在使用插件通过应用程序获取移动设备的状态和连接类型。但是这个插件只能在$ionicPlatform.ready内工作,至少发生在我身上,当我遇到控制器时,连接类型的结果是unknow

插件链接:Network Plugin 安装人员链接:CLI installer

代码

angular.module('starter', ['ionic', 'ngCordova'])
    .run(startApp)
    .controller('networkCtrl', networkCtrl);

startApp.$inject = ['$ionicPlatform', '$cordovaNetwork'];

function startApp($ionicPlatform, $cordovaNetwork) {

    $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();
        }

        var netInfo;
        netInfo = $cordovaNetwork.getNetwork();
        console.log(netInfo); //wifi, 4G, 3G, etc.

    });

}

networkCtrl.$inject = ['$scope', '$cordovaNetwork'];

function networkCtrl($scope, $cordovaNetwork) {

    var netInfo;
    netInfo = $cordovaNetwork.getNetwork();
    console.log(netInfo); //unknow

}

1 个答案:

答案 0 :(得分:2)

document.addEventListener("deviceready", function () {

中添加此内容
function networkCtrl($scope, $cordovaNetwork) {
    $scope.networkType = null;
    $scope.connectionType = null;
    document.addEventListener("deviceready", function () {
      $scope.networkType = $cordovaNetwork.getNetwork();
      if ($cordovaNetwork.isOnline()) {
        $scope.connectionType = 'Online';
      }
      else if ($cordovaNetwork.isOffline()) {
        $scope.connectionType = 'Offline';
      }
      else {
        $scope.errorMsg = 'Error getting isOffline / isOnline methods';
      }
    }, false);
 });