Angular failing to update $scope variable within controller

I need to implement a directive that allows file uploading directly to the browser

angular.module('angularPrototypeApp')
.directive('upload', ['$parse', function ($parse) {
return {
    restrict: 'A',
    scope: false,
    link: function(scope, ele, attrs) {

        var fn = $parse(attrs.upload);
        ele.on('change', function(onChangeEvent){
            var reader = new FileReader();

            reader.onload = function(onLoadEvent) {
                scope.$apply(function(){
                    fn(scope, {$fileContents: onLoadEvent.target.result} );
                });
            }

            reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
        })

    }
  };
}]);

The code snippet is sourced from:

The corresponding view appears as follows:

<progressbar class="progress-striped active" value="dynamic" </progressbar>
<input type="file" upload="parseInputFile($fileContents)">

In the controller, the following actions are taken:

angular.module('angularPrototypeApp')
.controller('Gc2xlsxCtrl', ['$scope', 'blockUI', function ($scope,  $timeout, blockUI) {

$scope.dynamic = 0;

$scope.parseInputFile = function($fileContents){
    $scope.$broadcast('fileUploaded', $fileContents);
}

$scope.$on('fileUploaded', function(event, fileContents) {
    if(fileContents !== undefined){
        blockUI.start();

        //Significant processing takes place here, lasting between 2 and 20 seconds
        for(var i = 1; i <= 100; i++){
            $scope.dynamic += 1;
        }

        blockUI.stop();
    }
});
}]);

The issue lies in the fact that the updates to $scope.dynamic do not reflect on the view until the entire method has completed execution. The same applies to blockUI. Despite being called at the beginning of the method, the view does not update accordingly. Any assistance on resolving this matter would be greatly appreciated!

Answer №1

In this section:

//a considerable amount of tasks are completed here, taking anywhere from 2 to 20 seconds
for(var i = 1; i <= 100; i++){
    $scope.dynamic += 1;
}

This code is synchronous and will not reflect any changes in the view until all the iterations are complete. Essentially, the loop incrementally updates the value of $scope.dynamic from 1 to 100, but these changes are only visible once the loop finishes running.

To allow the view to update while the task is in progress, asynchronous processing is required.

The most effective way to achieve this can vary. One approach could be to utilize $q in AngularJS.

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

Make a JSONP request with the MIME Type set to text/plain

I've been attempting to utilize JSONP for fetching a feed from a different domain. Despite knowing that the content type should ideally be JSON or JavaScript, it is currently set as text/plain and unfortunately, I lack control over the server settings ...

Development and staging setups tailored specifically for a JavaScript SDK

Currently, I am working with a Javascript SDK that is available on NPM. Alongside this, I have a Vue application utilizing the SDK and it's crucial for me to test them together across various pre-production environments (such as staging). Here are the ...

Unreachable prevState when utilizing the useState hook

I am currently working on a component where I need to capture the previousState of an element. However, no matter what I try, it keeps returning the initial value. This suggests that there is some re-rendering happening, causing it to constantly default to ...

"Animating a card to slide in from the left side upon clicking a button in a React app

How can we create a feature where, upon clicking "Apply Coupon" in Image 1, a window slides in from the left just above the webpage (as shown in Image 2)? Additionally, in Image 2, there is a blue transparent color on the webpage adjacent to this sliding w ...

Refreshing Ads JavaScript and Ad Placements with NextJS Navigation

My NextJS website utilizes a custom JavaScript provided by an ad provider for running ads. The script is typically structured like this: <script type="text/javascript" src="//cdn.adsite.com/static/js/ad.js" ></script> In ad ...

Video margins within a webview

After numerous attempts to embed a YouTube video in a WebView, I'm still struggling with a persistent small margin on the right side of the video. I've researched similar issues and attempted to address it through JavaScript adjustments without ...

Manipulating Object origin data

I'm unsure if this can be achieved. I am aiming to create a header and footer that remain the same while only switching the content pages. The resources I have at my disposal cover HTML, JS, CSS, and JQuery. Below is a simplified version of my curre ...

You must include an argument for 'model' in the Angular service

My service requires an id parameter for a route, but when I tried to access the route with the id, I encountered the error mentioned above. Any suggestions on how to resolve this issue? https://i.sstatic.net/FEcqo.png #request const apiBaseUrl = `${envir ...

The attribute 'id' cannot be found in the class 'Foods'

After examining my code below, I am attempting to remove clients from my data table by using checkboxes. Whenever I check a checkbox, I notice in the console that the object's properties are retrieved from the database. My goal is to delete by id, but ...

What could be the reason for the failure of the .is(":hover") method?

Here is some code I'm using to fade out certain elements on a webpage if the mouse hasn't moved for a period of time: idleTime = 0; var idleInterval = setInterval(function() { idleTime++; if (idleTime > 1) { var isHovered = $ ...

Refresh in AJAX, automated loading for seamless transition to a different page

Having an issue with the page not auto-refreshing, although it loads when I manually refresh. P.S Loading the page onto another page. Below is my HTML and AJAX code along with its database: The Trigger Button <?php $data = mysqli_query ...

Restricting the number of characters allowed for text messages and keeping track of the count

I am attempting to implement a character limiter for an html textarea using JavaScript. Additionally, I want to include a total character counter. Unfortunately, the code I have written isn't functioning as expected. Can anyone identify where my mist ...

Is there a way to control the text animation loop on iTyped, both starting and stopping it?

Currently utilizing React, MUI, along with iTyped The animation implemented involves backspacing text and typing the next word in a specified array until reaching the final word. I am looking to enable a click function on the div containing this animation ...

Upon registration, the user's information is successfully stored in the mongoDB database, even if the selected "username" is already in

I am currently working on a web application using the MERN stack. When registering a user with an existing email either through Postman or the front-end form, the user is not added to the database. The same logic is applied to check if the chosen username ...

Is there a specific minimum height that should be set for the equalHeight function to apply?

Despite trying everything, I can't seem to achieve the dreadful layout my designer has given me without using JavaScript! The issue lies with the positioning of the div #backgr-box, which needs to be absolutely positioned behind the #contenuto ( ...

Using jQuery to combine a variable with the image source in order to replace the image attribute

I am trying to create a script that will display a greeting message to the user based on their local time. I found a script on Stack Overflow, but I am struggling with updating the image source. When I try to replace the image source, I encounter the follo ...

The regular expression should consist of just letters and a single dot

Currently, I am working on creating a regular expression that allows only letters and one dot. However, there is a specific rule to follow: the dot cannot be located at the beginning or end of the string. For example: abc.difference This is what I attem ...

How can I reset the mousemove event in jQuery?

I need to create a mechanism where I can move a div by clicking on it, and then click again to stop the div in that position. However, encountering an issue when trying to move the div again as the mousemove event does not get activated. How can this be ...

Identify any fresh elements incorporated into the DOM following an AJAX call

I'm attempting to showcase a newly added div element within the DOM using AJAX. Through AJAX/PHP, I dynamically inserted some new buttons: <button type="button" id="viewPP_'.$index.'" onclick="viewPP('.index ...

Exploring the bind() method in the latest version of jQuery,

After upgrading my JQuery version, one of the plugins I was using stopped working. Despite trying to use the migrate plugin and changing all instances of bind() to on(), I still couldn't get it to work properly. The plugin in question is jQuery Paral ...