AngularJS / Cordova电池状态

时间:2015-08-10 14:19:46

标签: angularjs cordova ionic-framework ionic ngcordova

我试图显示设备的电池状态。我安装了以下插件:

Cordova Cordova plugin add-plugin-battery status

我在一个名为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
        });
    });
});

从HTML调用函数:

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

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

但状态未显示。代码有什么问题?

已编辑的代码:

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

2 个答案:

答案 0 :(得分:1)

我在goni​​c hub中上传了一个示例项目,了解Ionic框架中的电池状态battery-status如果您有任何疑问请告诉我

答案 1 :(得分:0)

controller("batteryController", function($scope, $rootScope, $ionicPlatform, $cordovaBatteryStatus) {
    $ionicPlatform.ready(function() {
        $rootScope.$on("$cordovaBatteryStatus:status", function(event, args) {
            if(args.isPlugged) {
                alert("Charging -> " + args.level + "%");
            } else {
                alert("Battery -> " + args.level + "%");
            }
        });
    });
}

插入并拔出电缆,您将获得输出:P