im trying to hook the battery manager object to a angular controller however the controller object doesnt seem to be updating when the promise by navigator.getBattery()
complete. here is what i came up with
(function(){
var app=angular.module('appBattery',[]);
app.controller('batteryController',['$window',function($window){
this.bat={};
this.level=this.bat.level;
$window.navigator.getBattery().then(function(battery){
setBattery(battery);
});
function setBattery(battery){
this.bat=battery;
console.log(this.bat);
}
console.log(this.bat);
}]);
})();
with this html
<div ng-app='appBattery'>
<div id="battery-status-bar" ng-controller='batteryController as battery'>
<div class="battery">
<div class="power">
{{battery}}
<div class="level"></div>
</div>
</div>
<div class="percentage">{{battery.bat.level}}</div>
<div class="time">{{battery.bat.chargeTime +':'+battery.bat.dischargeTime}}</div>
</div>
</div>
it can also be found on jsfiddle here
You can keep your controller as syntax. Check out my updated fiddle at https://jsfiddle.net/fnnruzjw/1/. There were a couple of issues at hand:
You needed to use $scope.$apply.
$window.navigator.getBattery().then(function(battery){
$scope.$apply(function() {
setBattery(battery);
});
});
Your this was referring to the wrong this (I changed it to be vm as is a popular convention).
You were losing the reference to your battery object when you were reassigning it. I used angular.copy to keep the reference.
function setBattery(battery){
angular.copy(battery, vm.bat);
console.log(vm.bat);
}