Conflict arises between Angular $scope and the file input type

I have been attempting to convert a file into a byte array using AngularJS. The conversion process is successful and I am able to add the byte code and filename to an array ($scope.FileAttachments). However, there seems to be an issue with ng-repeat not working at the right time when trying to display the attached file. It's interesting to note that ng-repeat works fine when any other event occurs within the view.

HTML Code

<input id="File1" ng-model="File1" onchange="angular.element(this).scope().file1Upload()" type="file" />

<table  class="table table-striped table-bordered table-list">
    <thead>
        <tr>
             <th>Name</th>
        </tr>
    </thead>
    <tbody id="tblAttachments">
         <tr ng-repeat="item in FileAttachments  track by $index">
             <td>{{item.AttachmentDescription}}</td>
          </tr>
    </tbody>
</table>

AngularJS Controller's Code

$scope.FileAttachments = [];
var fileData;

function getBuffer(resolve) {
     var reader = new FileReader();
     reader.readAsArrayBuffer(fileData);
     reader.onload = function () {
          var arrayBuffer = reader.result
          var bytes = new Uint8Array(arrayBuffer);
          resolve(bytes);
     }
}


$scope.file1Upload=function() {
     var files = document.getElementById("File1").files;
     fileData = new Blob([files[0]]);
     var promise = new Promise(getBuffer);
     promise.then(function (data) {
          $scope.FileAttachments.push({
              "AttachmentDescription": files[0].name.toString(),
              "FileValue": data.toString()
          });
     }).catch(function (err) {
          console.log('Error: ', err);
     });
}

Answer №1

A helpful tip: remember to call $scope.$apply() when stepping outside the bounds of your controller's scope.

$scope.uploadFile=function() {
      var files = document.getElementById("FileUpload").files;
      fileData = new Blob([files[0]]);
      var promise = new Promise(getBuffer);
      promise.then(function (data) {
          $scope.$apply(function () {
              $scope.Files.push({
                   "Description": files[0].name.toString(),
                   "Value": data.toString()
               });
          });
      }).catch(function (err) {
           console.log('Error: ', err);
      });
 }

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

Having trouble retrieving the 'WWW-authenticate' header from the $http response in Angular?

Can someone explain why the 'WWW-Authenticate' header appears to be null in the response, even though it is visible as a stringified object in Chrome dev tools? On the server side, I have set the WWW-Authenticate header and configured the necess ...

Is there a way for me to extract all the elements within an object nested inside an array and then append them to another array?

I'm currently facing a challenge that's bothering me quite a bit. My skills in handling JSON data manipulation are not up to par. The problem I'm dealing with involves an array of multiple objects, each containing some data. Within these ob ...

Access Sharepoint from an external site

Looking for assistance with a SharePoint list containing columns for Name, Position, Office, and Salary. Upon logging in with specific credentials to the SharePoint website, I need to retrieve all items from the list and showcase them on my own website. ...

When accessing the defaultValue property of a select element, it will result in

Here is a typical HTML dropdown menu: <select name="email" id="email"> <option value="2" selected="selected">Before redirecting to PayPal</option> <option value="1">After payment is successful</option> <opti ...

Difficulty in sharing cookies among subdomains

I have successfully stored my visitors' style sheet preference in a cookie, but I am facing an issue with sharing the cookie across subdomains. Even after specifying the domain, the cookie does not seem to be shared. What could be causing this proble ...

Is there a tool available that can convert the string "foo:blah" into JSON format?

My goal is to transform a human-readable list like the following: Enabled: Yes Server: example.com Port: 8080 Authenticated Proxy Enabled: 1 ... into a sanitized JSON object as shown below: { "Enabled": "Yes", "Server": "example.com", "Port" ...

What is the best way to retrieve the second element based on its position using a class name in Jquery?

DisablePaginationButton("first"); The statement above successfully disables the first element that is fetched. DisablePaginationButton("second"); ===> not functioning function DisablePaginationButton(position) { $(".pagination a:" + position).ad ...

Automatically generated error notifications for Express-Validator

I am looking to implement an Express API and incorporate request input validation using express-validator. Here is my current validation middleware: protected validate = async (request: Request, response: Response, next: NextFunction): Promise<void> ...

"Unlocking the potential of JSON: A guide to retrieving and displaying three specific fields in

My PHP service is returning the following data: [[1,"16846"],[2,"16858"],[3,"16923"],[4,"16891"]] Within my HTML, I have ajax set up to fetch this information; $.ajax({ type: 'POST', url: 'getDadosGrafico.php', ...

Is it possible to manipulate the content inside a div tag using JavaScript in HTML?

What is the most efficient way to dynamically adjust a data offset value within an HTML tag using JavaScript? For example: <div class="box" data-offset="2s"></div> I am looking to update the value within the data-offset attribute based on s ...

my initial attempt at using Firebase cloud functions

I'm currently attempting to create my first Firebase Cloud Function. My goal is to take the value of the 'name' field from the 'amr' document and add it to the 'ahmed' document under a new field called 'newName' ...

Error: Protractor failed to synchronize with the page within the allotted 11-second timeframe

Encountering an issue with my Protractor tests. The angular app I am working on utilizes $timeout for continuous polling from a server, resulting in the following error message during test runs: There was a webdriver error: Error Timed out waiting for Pr ...

Concentrate on what comes next

Within my JavaScript code, I have the following line: $('input')[$('input').index(this)+9].focus(); I intended for this line to focus on the next element. However, when it executes, I encounter the following error: Error: [$rootSc ...

Mastering the art of integrating HTML5's localstorage feature with Jquery's select2 plugin

Is it possible to integrate HTML5's localstorage method with Jquery's select2 plugin? Currently, all entered data disappears when the browser/tab is closed, leading to potential confusion if you forget what was entered. Here is an example of my ...

Creating a chart with multiple series in canvas js through looping

I'm currently working on creating a multi-series chart using Canvasjs. I've encountered an issue where I can't include a loop inside the dataPoints and have had to manually code everything. Is there a way to utilize for loops in this scenari ...

Error: The 'replace' property of null cannot be read in select2

In my Node Express app, I am incorporating select2, and encountering an error when supplying an array as the data source with data: dataBase. The issue arises as Uncaught TypeError: Cannot read property 'replace' of null. Although using an ajax ...

Enhancing a Pie Chart Dynamically with Ajax using Highcharts

I need assistance with updating the data for the pie chart when a list item is clicked. The issue arises when using dynamic values from $cid in data.php. For example, user_student.cid = 1 works correctly, but if I use user_student.cid = $cid, it doesn&apos ...

Issue with Webpack: error message "Cannot read property 'readFile' of undefined" is causing no output files to be generated

When utilizing version webpack > 5, the configuration for my appDevMiddleware.js is as follows: const path = require('path'); const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware' ...

What is the process for creating a transparent default color theme in MUI?

I'm looking to make an element's background color the primary main color with some transparency using Material-UI. I've attempted a couple of methods, but unfortunately neither have worked for me. Any suggestions or guidance would be greatly ...

If the Ajax request is successful, scroll to the bottom of a Div using jQuery

An interesting scenario arises with this Div that contains user messages, where the newest message always appears at the bottom of the Div and triggers a scroll bar if the message count exceeds the height of the div: <div class="list-group-message" s ...