AngularJS Question

Network plugin ngCodova don't work into controller

I am using a plugin to get the status and connection type my mobile device through an application. But the plugin only works within

$ionicPlatform.ready
, at least that happened to me, when I run into the controller, the result of the type of connection is
unknow
.

Plugin link: Network Plugin
Installer link: CLI installer

Code



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

}

Answer

Add this inside 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);
 });
Comments