Monitor the change in FileReader().readyState using AngularJS

Below is the AngularJS code I have written to read a local file.

var files = document.getElementById("file");

files.addEventListener("change", handleFile, false);

function handleFile(event) {
    SpinnerService.upload(); // Display loading spinner

    var file = event.target.files[0];
    var reader = new FileReader();

    $timeout(function() {
        scope.readyState = reader.readyState;
    });

    reader.onload = function(event) {
        // Read the contents of the file
    };

    reader.readAsArrayBuffer(file);

    scope.$watch("readyState", function(newVal) {
        if (newVal == 2) {
            SpinnerService.hide(); // Hide loading spinner
        }
    })
}

During the file reading process, the value of reader.readyState changes from 0 to 1 and then to 2. More information about this can be found at https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readyState.

The code successfully reads the file content. However, the $watch on readyState does not seem to work as expected. Is there an alternative approach to monitor the changes in readyState? Your assistance is appreciated. Thank you!

Answer №1

I recommend against setting the watch in the handler function, as it will create a new watch each time it is triggered. Instead of assigning scope.readyState to reader.readyState directly, consider it as setting x = 2 and waiting for it to change.

Here's an alternative approach:

// initialize empty object
scope.reader = {}

var files = document.getElementById("file");
files.addEventListener("change", handleFile, false);

// set watch on object property
scope.$watch("reader.readyState", function(newVal) {
    if (newVal == 2) {
        SpinnerService.hide(); // Hide loading spinner
    }
})

function handleFile(event) {
     SpinnerService.upload(); // Show loading spinner

     var file = event.target.files[0];
     var reader = new FileReader();

     // assign reader to object
     scope.reader = reader;

     reader.onload = function(event) {
         // Read the file
     };

     reader.readAsArrayBuffer(file);
 }

I also agree with wero's suggestion being the best solution

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

Is it possible for you to pinpoint the mistake in the code below?

I've been trying to locate an error in the function but have been unable to do so. As a beginner in this area, I would appreciate your patience. <html> <head><title>print names</title> <script langua ...

Styling the scrollbar for the PDF element on an HTML page

I have a div that contains an object "linked" to a .pdf file. Is it possible to customize the scrollbar style using CSS or JavaScript/jQuery? <div id="container"> <object data="document.pdf" type="application/pdf" ...

How should a successful post request be properly redirected in React?

I am in the process of learning React and currently working on a small project. I have set up a NodeJS server to handle my requests, and now I am facing an issue with redirecting the user after a successful login. I successfully dispatch an action and upda ...

Problem encountered when attempting to utilize the spread operator within .vue files in an Elixir Phoenix 1.3 application

I'm facing an issue while building Vue.js components that involve using the spread operator to map states from Vuex within my Phoenix 1.3 application. The JavaScript compile errors I encountered are causing some roadblocks: 26 | }, 27 | compu ...

angular $stateProvider behaving unexpectedly with routing

Within my main file titled index.html, I have incorporated the following basic markup... <body ng-app="starter" ng-controller="AppCtrl"> <div ui-view></div> </body> In my separate file called app.js, I am utilizing $stateProvi ...

I am currently facing an issue with validating forms in JavaScript Document Object Model (DOM)

Whenever I click on a field and move to another one, the span tag turns red. Then, after pressing the submit button, an alert message pops up. However, if I turn the span red, fill in the field, and press the submit button, it shows success even if other f ...

NG6002 error: This error is showing up in the imports of AppModule, even though it has its own set of issues

Running Angular 12 locally is smooth with no errors in the project build. Local Configuration: Angular CLI: 12.0.5 Node: 12.16.3 Package Manager: npm 6.14.4 OS: win32 x64 Angular: 12.0.5 However, when attempting to build the project on a Linux se ...

Breaking down a number using JavaScript

Similar Question: JavaScript Method for Separating Thousands I'm looking to find a way to separate numbers by a thousand using JavaScript. For example, I would like to turn "1243234" into "1 243 234", or "1000" into "1 000" and so on. (sorry for ...

The leaflet_Ajax plugin is constantly searching for the default marker symbol located at js/images/marker-icon.png

Although I'm relatively new to Leaflet, I have experience creating interactive maps in the past. Recently, I've been working on a project involving displaying GPS data from a UAV. The UAV transmits location information to a server, which then ret ...

The online server is unable to access the route from the ajax function in a separate JavaScript file

I am currently working on a Laravel project where each view page has its own separate JS file. However, I have encountered an issue when trying to access route functions from AJAX post or get calls on the online server (Digital Ocean). The error message I ...

When the onClick event on one element triggers a change in another element within the

I apologize if the title is not clear. I have a React component with buttons and text, which I have used three times. My goal is for each button to display its respective text when clicked, while hiding the texts associated with the other buttons. While m ...

How can I prevent right-clicking with Ctrl+LeftMouseClick in Firefox on MacOS?

I'm looking to implement a shortcut using Ctrl+LeftMouseClick in my React project. It functions perfectly on Chrome on my Mac, but in Firefox the shortcut initiates a right mouse click (event.button = 2). I believe this may be due to MacOS's Rig ...

What could be causing the state to not update as anticipated?

I am currently in the process of developing a TicTacToe game and have a requirement to maintain the current player in state under the name currentPlayer. The idea is that after one player makes a move, I need to update currentPlayer to represent the opposi ...

The dynamic JavaScript in Bootstrap 4 seems to be malfunctioning, despite working perfectly in Bootstrap 3

I am currently implementing a dynamic modal feature using the code snippet below: // Show Ajax modal with content $(document).on('click', '[data-modal]', function (event) { event.preventDefault(); $.get($(this).data('moda ...

Unable to call Success function in JQuery AJAX request

Here is a simple JQuery ajax request I am working on: $.ajax("../ajax/data/items.json", { success: setContent, type: "GET", dataType: "json" }); function setContent(data, status, jqxhr) { alert("Hello!"); } The json file loads successfully with a 200 r ...

I'm running into an issue with my React component where it is rendering before the state is set, causing it to fail. Is there a

Is it possible for me to achieve what I've been attempting for the past week? I feel like I'm so close, yet still can't quite reach my goal. Could it be that what I'm trying to do is impossible? I am using reactjs and next js (although ...

The child module invokes a function within the parent module and retrieves a result

Guardian XML <tr [onSumWeights]="sumWeights" > Algorithm sumWeights(): number { return // Calculate total value of all weights } Offspring @Input() onTotalWeights: () => number; canMakeChanges() { return this.onTota ...

Create various designs for a section of a webpage

My goal is to create a coding playground using flex-box to position different panels. Here is an example in JSBin, with the following html code: <div class="flex-box"> <div class="col" id="html-panel"> <p>html</p> </div& ...

A new module is unable to load Angular Material

Recently, I developed an Angular material module similar to a core module. import { NgModule} from '@angular import {MatCheckboxModule} from '@angular/material/checkbox'; @NgModule({ imports: [ MatCheckboxModule ], exports: [ ...

FlexNav excluding

I have implemented FlexNav for my website navigation. The demo I used sets the width of top-level menu items to 20%, which works well with five menu items. .flexnav li { . . . width: 20%; } However, in my menu, the text lengths of the top ...