Struggling to arrange files in a neat array with Angular.js

Encountering an issue while attempting to upload multiple files using ng-file-upload in Angular.js. Below is a breakdown of my code:

<input type="file" class="filestyle form-control" data-size="lg" name="bannerimage" id="bannerimage"  ng-model="file" ngf-pattern="'image/*'" accept="image/*" ngf-max-size="2MB" ngf-min-height="100" ngf-resize="{width: 100, height: 100}" custom-on-change="uploadFile" required="required" ngf-select="onFileSelect($file);" ngf-multiple="true">
</div>
<label for="bannerimage" accesskey="B" ><span class="required">*</span> View Image</labe
<div style="padding-bottom:10px;" ng-repeat="pht in stepsModel">
<img ng-src="{{pht.image}}" border="0" name="bannerimage" style="width:70px; height:70px;" id="imgId">
</div>

The corresponding controller-side code looks like this:

$scope.stepsModel = [];
    $scope.allFiles=[];
    $scope.uploadFile = function(event){
        console.log('event',event.target.files);
        var files = event.target.files;
        for (var i = 0; i < files.length; i++) {
         var file = files[i];
             var reader = new FileReader();
             reader.onload = $scope.imageIsLoaded; 
             reader.readAsDataURL(file);
     }
    };
    $scope.imageIsLoaded = function(e){
    $scope.$apply(function() {
        var data={'image':e.target.result};
        $scope.stepsModel.push(data)
    });
}
$scope.submitImage=function(){
    console.log('all files',$scope.allFiles);
}
$scope.onFileSelect = function($files) {
         $scope.allFiles.push($files);

}

The issue arises when inspecting the image URLs in the console message within the submitImage function:

all files [Blob, null, Blob, null, Blob]
0: Blob

1: null   
2: Blob  
3: null    
4: Blob 

Objectlength: 5v

Despite uploading only 3 files, the length displayed is 5, indicating a non-sequential order. Assistance needed to ensure all files are listed serially. Thank you.

Answer №1

Before proceeding, it is important to identify the reason for the presence of null elements in the array. Add a logging feature in the onFileSelect function to examine the contents of the allFiles array after each file selection.

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

Using the `forEach` method nested within another `forEach

I'm facing an issue with the useEffect hook where it seems to not be rendering correctly. My cardArticle is only concatenating the last array and that's it. Below is the code snippet: const [articles, setArticles] = useState([]); const [cardA ...

Building an interactive accordion dropdown menu for the sidebar using AngularJS, moving away from traditional jQuery solutions

As I delve into learning about AngularJS, I find myself faced with a sidebar template that uses jQuery to create a dropdown. However, I strongly believe that there must be an AngularJS solution for this. I continue to encounter challenges with this task, b ...

Altering the playback of a flash object using HTML or JavaScript

Can the playback speed of a flash object be adjusted without recompiling the object, like through HTML attributes or JavaScript? Appreciate any help in advance ...

Integrate JQuery-Ui into an Angular 7 application using an external .js file

I'm currently working on an Angular 7 project and facing some challenges while trying to integrate the JQuery-Ui plugin. I have successfully installed both JQuery and the plugin, and added them to the scripts array in my angular.json file. Even though ...

What is the best way to retrieve JSON key/value pairs instead of an array?

I am working on retrieving data from a Google Spreadsheet using App Script and have set up a DoGet function. Currently, I am getting an array of data but I need it in JSON key-value pairs format. The table in my Google Sheets is structured as follows: Th ...

Use the .replace() method to eliminate all content on the page except for the table

Extracting a table from a page that has been loaded through .ajax() in queue.htm has proven to be challenging. I am attempting to utilize .replace(regex) in order to isolate the specific table needed, but the process is unfamiliar to me. $j.ajax({ ...

Could someone provide insight into the functionality of this specific segment of JavaScript/Ajax code?

Currently, I am diving into Ajax and exploring this specific example. I am struggling to comprehend the syntax variable = function(){; how does this code actually work? How can a function be assigned to a variable? xmlhttp.onreadystatechange=function() ...

Encountering difficulties in the installation of a package within Next JS

Can anyone assist me with this issue I'm facing while trying to install styled-components on Next JS? I keep getting an error after entering npm install --save styled-components: npm ERR! Unexpected end of JSON input while parsing near '...ry.np ...

What could be the root cause behind the generation of a transient script file?

Currently, I am utilizing an application that utilizes both client-side and server-side code in JavaScript. Debugging the client-side code with a "debugger" statement in Visual Studio 2005 has been successful. However, when attempting to debug the server-s ...

Click on a button to display the corresponding DIV while hiding the rest, all achieved with the power of Vue

I'm seeking guidance as a newcomer to Vue, so please bear with me if my question appears simplistic. My scenario involves a set of buttons and corresponding div elements. The goal is to show a specific div when its associated button is clicked, while ...

What is the best way to retrieve a state variable within the getServerSideProps() function in NextJS?

Introduction Greetings everyone, I am a newcomer to NextJS. Currently, I am in the process of developing a weather application that utilizes external APIs. My main task involves fetching data from an API and displaying it on the frontend. Desired Function ...

Using a PHP variable within a JavaScript function to incorporate its value into a select field, ultimately generating a response using JavaScript

As I work on developing a shopping cart, I have successfully stored the total value of the items in the cart in a PHP variable named $total. I attempted to transfer this value into a JavaScript variable labeled Shipping fee. Subsequently, I created a form ...

When I attempt to utilize the API, the JavaScript implementation of a <script src=...> element seems to interfere

Within one of my HTML files, I encountered the following line near the top: <script src="//maps.google.com/maps/api/js?key=apikey"></script> The API key is currently hardcoded in this file, but I would like to use a configuration option store ...

Locate all inputs containing a special attribute name, wherein a portion of the name corresponds to a JavaScript variable

$("td[id^='td' + myvar + '_']") Can someone help me with a solution to substitute the static value of 0 in this code snippet with the dynamic variable myvar? Thanks! ...

Exploring the functionality of AngularJS routing on a webpage

Testing the routing functionality of AngularJS while creating a web page. The index.html will contain links to Home, Courses, and Students. Clicking on each link will load its respective HTML using AngularJS routing. The student information is stored in ...

What is the best way to define a dynamic model name in AngularJS?

I am looking to dynamically populate a form with custom questions (check out the example here): <div ng-app ng-controller="QuestionController"> <ul ng-repeat="q in Questions"> <li> <div>{{q.Text}}</div> ...

Having trouble accessing the 'checked' property of the checkbox

I've been developing a web application using Vite, JavaScript, jQuery, and Bootstrap. I'm facing an issue where the jQuery .is(':checked') function is not working as expected on one specific page. Despite the checkboxes being checked, t ...

The TS2583 error in TypeScript occurs when it cannot locate the name 'Set' within the code

Just started my Typescript journey today and encountered 11 errors when running tsc app.ts. Decided to tackle them one by one, starting with the first. I tried updating tsconfig.json but it seems like the issue lies within node_modules directory. Any help ...

The JSON data rendered by Angular is causing disturbance

I am trying to create JSON from a multi-array in the following format: var qus ={ { "qus" :"what is your name?", "option1" : {"ans" : Alex, "cor:"false"}, "option2" : {"ans" : Hervy, "cor:"false"}, "option3" : {"ans" : Rico, "cor:"true"}, "option4" : {" ...

Is it possible to generate CSS classes dynamically?

Highlighted text I'm currently learning and I'm interested in generating 100 CSS classes dynamically. I'd like to achieve something similar to this: for (i=0; i<100; i++) { // generate CSS class const newBackgroundColor = dynamicBack ...