Exploring the Battery Manager functionality within AngularJS

I am attempting to connect the battery manager object to an Angular controller, but for some reason the controller object does not update when the promise provided by navigator.getBattery() is complete. Below is the code I have written:

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

Here is the corresponding 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>

The above code can also be found on jsfiddle here

Answer №1

If you want to maintain your controller's syntax, take a look at the updated fiddle I provided here: https://jsfiddle.net/fnnruzjw/1/. There were a few issues that needed addressing:

It was necessary to utilize $scope.$apply.

$window.navigator.getBattery().then(function(battery){
$scope.$apply(function() {
    setBattery(battery);
  });
});

Your reference to "this" was incorrect (I changed it to be vm as is commonly done).

You were inadvertently losing the reference to your battery object when reassigning it. To retain the reference, I used angular.copy.

function setBattery(battery){
  angular.copy(battery, vm.bat);
console.log(vm.bat);
}

Answer №2

Set energySource equal to $scope.source (don't forget to inject $scope into your controller as well). Additionally, remember to execute $scope.$apply(). Essentially substitute this with $scope.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for passing a function to express-handlebars within a node.js-express application

I've been attempting to pass a function in express-handlebar, but for some reason it's not working. In my setup, I have app.js serving as the server file and index.handlebars as the handlebar file. In app.js: const express=require('expres ...

What steps should I take if the slackbot is properly functioning after being invited to the channel?

Using an OAuth2 token I am looking to automate the process of sending data from Google Sheets via Slackbot. Even though I have set up tokens and connections, I find that I still need to manually input the channel id into my script. In order to streamline ...

Are there any alternatives to ui-ace specifically designed for Angular 2?

I am currently working on an Angular2 project and I'm looking to display my JSON data in an editor. Previously, while working with AngularJS, I was able to achieve this using ui-ace. Here is an example of how I did it: <textarea ui-ace="{ us ...

What are the problems with Internet Explorer in Selenium WebDriver?

Currently dealing with a mouse-over issue in IE while using webdriver code. The functionality works smoothly in Chrome and Firefox, however, the problem arises only in IE. How can I resolve this? Initially focusing on an element and then clicking on a li ...

Sending JSON Data from C# to External JavaScript File without Using a Web Server

Trying to transfer JSON data from a C# (winforms) application to a static HTML/JavaScript file for canvas drawing without the need for a web server. Keeping the HTML file unhosted is preferred. Without involving a server, passing data through 'get&ap ...

Optimizing the Placement of Dynamic Google Maps

After setting up a responsive Google map using this jsFiddle and guidance from this stack overflow post, I encountered an issue. How can I keep the map centered on the marker across various viewports and browser sizes? I came across a solution in this res ...

Preventing a timer from pausing in NextJS during periods of inactivity

Recently, I developed a straightforward timer application using Next.js that should continue counting even when the browser window is inactive. However, I noticed that if I switch to another window for approximately 5 minutes, the timer stops counting whi ...

VueJS - Iterating over a list within a vue component causes the list to be empty

Having encountered an issue with the answers provided to my question from yesterday, I have decided to create a new query with additional details. To review the original question, please visit: VueJS - using mustache template strings inside href attribute ...

Is there a way to modify the MimeType using the $http service in Angular by using the XMLHttpRequest.overrideMimeType() method?

Looking to bring this sample to Angular. Planning on switching to $http from an XMLHttpRequest object. The current code is: var req = new XMLHttpRequest() req.overrideMimeType('text/plain; charset=x-user-defined'); Curious about how to override ...

Updating an existing value with a cascading dropdown list

My JavaScript code dynamically populates a dropdown list called District based on the selection made by the user in another dropdown list called Department. Here is the snippet of the code: Firstly, I populate the Department dropdownlist and add a ' ...

Unable to locate template or render function for Vue Draggable Next component

Looking to incorporate Vue Draggable Next into a Vue 3 example page but encountering some challenges. I've attempted to follow the instructions in the repository. However, I ran into issues when importing the Vue Draggable Next component and had to re ...

Experimenting with the inner workings of a method by utilizing vue-test-utils alongside Jest

Is there a way to properly test the internal logic of this method? For instance: async method () { this.isLoading = true; await this.GET_OFFERS(); this.isLoading = false; this.router.push("/somewhere"); } This method toggles isLoading, ...

The output of the Node.js crypto.pbkdf2 function may not match the result obtained from CryptoJS.PBKDF

Currently, I am utilizing PBKDF2 on both the frontend with CryptoJS and the backend with Node.js. Despite using the identical salt, algorithm, number of iterations, and password, the derived keys are turning out to be different. Below is the code snippet ...

What are some ways to create a flashing effect for text in HTML and JavaScript?

Although flashing text is typically prohibited in many places, my client has requested it for a project. I need to create one line of text that flashes using HTML and JavaScript. The text should appear and disappear within seconds, repeating this cycle. I ...

Launch a fresh fancybox once the previous one has exited

I am currently facing an issue with my password change process through a fancybox window. Whenever a user enters the wrong password, a "Wrong Password" iframe opens up. However, the challenge arises when I try to reopen the "Password Change" iframe after c ...

Angular material table cell coloring

Here is my current setup: I have an array of objects like this: users : User []; average = 5; compareValue (value){ ...} And I am displaying a table as shown below: <table mat-table [dataSource]="users"> <ng-container matColumnDef= ...

Ways to circumvent route handling in Angular UI Router

I'm currently developing a web application where most of the functionality is implemented as an AngularJS single-page application. However, there are also some static content pages that are served traditionally. The navigation within the SPA utilizes ...

Encountering a problem with lazy loading of module routing paths. Issue arises when attempting to navigate to http://localhost:4200

AppLazyLoadingMoudle import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; const ROUTES : Routes = [ /* ProductModule (defined in the feature module) is loaded lazily when navigating ...

Retrieve the public URL from the index.html file following the build process

In my project, I utilized ReactJS by creating an app with the command npx create-react-app my-app. To build the project, I used yarn build. Within the package.json file, the scripts section appears as follows: "scripts": { "start": "react-scripts sta ...

Develop a personalized event that is compatible with all types of selectors

If I have a simple script that changes the background color of an element when clicked: $(".foo").on("change.color", function() { $(this).css("background-color", "red"); }); $(".foo").click(function() { $(this).trigger("change.color"); }); Currently ...