Search code examples
angularjscordovaionic-frameworkngcordova

AngularJS/Cordova battery status


I'm trying to display the battery status of my device. I have installed the following plug-in:

Cordova Cordova plugin add-plugin-battery status

I have wrote a controller in a separate file named batteryStatus.js:

myApp.controller("BatteryCtrl", function($scope, $rootScope, $ionicPlatform, $cordovaBatteryStatus) {

    $ionicPlatform.ready(function() {
        $rootScope.$on("$cordovaBatteryStatus:status", function(result) {
            var batteryLevel = result.level;       // (0 - 100)
            var isPluggedIn  = result.isPlugged;   // bool
        });
    });
});

The call of the function from HTML:

<script src="js/batteryStatus.js"></script>

<div ng-controller="BatteryCtrl">
   Status: {{batteryLevel}} %
   Pluged In: {{isPluggedIn}}
</div>

But the status is not shown. What is wrong with the code?

Edited Code:

myApp.controller("BatteryCtrl", function($scope, $rootScope, $ionicPlatform, $cordovaBatteryStatus) {
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        $ionicPlatform.ready(function() {
            $rootScope.$on("$cordovaBatteryStatus:status", function(event, args) {
                console.log(args);
                $scope.batteryLevel = args.level;
                console.log($scope.batteryLevel);
                $scope.isPluggedIn = args.isPlugged;
                console.log($scope.isPluggedIn);        
            });
        });
    }
});

Solution

  • I uploaded a sample project in git hub for battery status in Ionic framework battery-status if you have any queries please let me know