Unable to assign a value to an indexed property in 'FileList': Setter function for index properties is not enabled

angular.module('myApp')
    .directive('fileModel', ['$parse', 'uploadService','messageService','CONF', function ($parse, uploadService,messageService,CONF) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var model = $parse(attrs.fileModel);
                var modelSetter = model.assign;
                element.bind('change', function () {

                    var file = element[0].files[0];

                    var fd = new FormData();
                    fd.append('file', file);
                    console.log(fd)

                    self.isDisabled = true;

                       ParkingService.uploadImage(fd).then(
                            function (response) {
                                response = JSON.parse(response);
                                element[0].files[1] = response;
                                console.log(response)
                                    if (response.message !== 'ERROR') {
                                        // self.image = response.result;
                                            messageService.toasterMessage(CONF.TOASTER_TOP_RIGHT,CONF.TOASTER_SUCCESS,"Success Upload File");
                                    }
                                    else {
                                        messageService.toasterMessage(CONF.TOASTER_TOP_RIGHT,CONF.TOASTER_ERROR,response.result);

                                    }
                                }
                        );

                    scope.$apply(function () {
                        modelSetter(scope, element[0].files);
                    });
                });
            }
        };
    }]);

how can the variable "response" be assigned a value?

element[0].files[1] = response;

This method works in older versions of Safari and Chrome but it might not be fully supported in newer versions of Chrome.

Answer №1

Chrome and Firefox have recently implemented restrictions on setting new indexes on NodeList and FileList, possibly part of a larger effort to align these "array-like" structures with JavaScript standards. This is indicative of the direction in which browsers are evolving.

Although running in non-strict mode can revert this behavior, it may not be practical in a transpiled JavaScript environment, nor necessarily recommended.

The most effective solution would be to convert the FileList to an array using

const files = Array.from(element[0].files)
or simply
const files = [...element[0].files]
(depending on browser compatibility and transpilation requirements).

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

Attempting to perform recursion on two functions simultaneously may result in one of the functions being undefined

There is a page on my site that clients tend to keep open for long periods of time without refreshing, sometimes over 24 hours. Some of the actions on this page require a valid PHP session, so I created a simple set of functions to check this every 10 minu ...

What is preventing me from getting jQuery UI 1.8.20 dialog to function on JSFiddle?

My attempt to implement jQuery UI dialog in JSFiddle has been unsuccessful, consistently resulting in a dialog opening error caused by a deep-seated issue within jQuery UI: Uncaught TypeError: Cannot read property '3' of undefined. Although I am ...

Tips for transferring information between two components when a button is clicked in Angular 2

I am currently working on a code that displays a table on the main page with two buttons, "Edit" and "Delete", for each row. When the Edit button is clicked, a modal opens up. My question is, how can I pass the "employee id" of a specific employee to the ...

Develop an HTML table using either JSON or jQuery in Javascript

JavaScript is a bit of a mystery to me right now - I could really use some assistance in overcoming this obstacle that has me pulling my hair out! I'm struggling with constructing HTML code using JSON data. It's just not clicking for me at the m ...

Having trouble loading select2 using PHP/Ajax/JSON even though I can see the data in the inspector

I encountered a puzzling issue after deploying my web application from a Windows (XAMPP environment) to a Linux Server. Despite everything working perfectly on Windows, I am now facing a frustrating problem that has left me stumped. I have scoured through ...

Can all AngularJS modules be seamlessly integrated with Browserify?

After discovering a module called angular-timeline, I proceeded to install it by running npm install angular-timeline --save. Following that, I used the command require('angular-timeline'). var angular = require('angular'); require(&ap ...

Show a selection of assorted files stored in the database

router.get("/alw", function(req, res){ Product.find({"category": "alw"}, function(err, allProduct){ if (err){ console.log(err) } else { res.render("products/alw", {products ...

What strategies can be utilized to condense code when needing to adjust a className based on various props?

I am looking to condense this code, particularly the [if~else if] block, in order to dynamically change a className based on different props passed. export default function Button(props) { const { name, height, color, bgColor } = props; let className = ...

Encountered a Dojo error of "TypeError {stack: (...), message: "undefined is not a function"}" when attempting to display a gif during an ajax load

I've been attempting to display a loading gif while an ajax call is in progress. However, I encountered an error at the show statement and the console displayed: TypeError {stack: (...), message: "undefined is not a function"} Here's my code sn ...

Utilizing Aramex API in React Native: A Step-by-Step Guide

Currently, I am tackling an eCommerce venture that requires the utilization of Aramex APIs for shipping and other functionalities. Since my project is being developed in React Native, I am seeking guidance on how to integrate Aramex APIs into this framewo ...

PHP - The variable $_SESSION['var1'] has not been set within the index.php file

My index.php page is causing me some confusion. <?php session_start(); if (!isset($_SESSION['var1'])) { echo "session not started..."; die(); } else { echo "session started"; die(); } ?> Within the page, there is a login form that connec ...

How can we determine which MenuItems to open onClick in a material-ui Appbar with multiple Menus in a React application?

While following the examples provided on the material UI site, I successfully created an AppBar with a menu that works well with one dropdown. However, upon attempting to add a second dropdown menu, I encountered an issue where clicking either icon resulte ...

Vue JS causing page to flash briefly before disappearing

I recently started exploring Vue and I'm working on creating a basic search function that takes a user input query and displays all matching users. To help me with this, I've been following a video tutorial for guidance. Despite not encounterin ...

Submitting a POST request from a Typescript Angular 2 application to a C# MVC backend

Having trouble passing a payload using Typescript service in an http.post request Here is my TypeScript code: saveEdits(body: Object): Observable<Animal[]> { let bodyString = JSON.stringify(body); let headers = new Headers({ 'Content- ...

Ways to retrieve the highest date value in an array

I'm running into an issue where I am trying to find the maximum day in an array of dates, but for some reason it keeps returning either Invalid Date or null. I'm not sure what's going wrong. Do you think I should convert the values to a diff ...

Is there a way to incorporate the use of quotation marks within the ng-bind directive in AngularJS?

Is there a way to insert phoneNo["phoneno"] into an HTML input using the ng-bind directive in Angular? While {{phoneNo["phoneno"]}} can display the data, it results in a syntax error when I try to put it like this: <input class="form-control" type="t ...

Guide to continuously polling a GET request in JavaScript until the response status is successful

In my JavaScript code, I have a function that utilizes AJAX to send a GET request. The response from the request can be either success, fail, or in process if the job is still running. I want this function to continuously send the GET request every few s ...

Protractor - Error: prop is undefined

Need assistance in identifying an error. Currently, I am learning Protractor and attempting to create a basic test using Page Object. //login_pageObject.js let loginContainer = function() { this.usernameInput = $("input.login-form-01"); this.passwordInp ...

JS selection-dropbox

As someone who is relatively new to JS, I am struggling a bit. The goal of the code is to display items with specific content (ALL, A, B, C). While the code works fine with buttons, I can't seem to get it to work with a 'Dropdown-select', ...

Importing a JavaScript file into another JavaScript file as text in React Native can be a convenient way

In my project, I have a file named MyFirstPage.js that contains the following code snippet: renderCards() { let icon = this.state.icon; .... .... .... } This code is responsible for rendering cards within the main render function. However, as the ...