Issue with file upload: The view is not refreshing in response to non-angular events

I am having an issue with my upload component where the view is not updating when the onchange event fires. Even though I can see the file names being logged, nothing is happening on the screen.

My approach involves using a directive so that I can easily integrate the file uploader into any project by simply adding

<upload url='/fileserver'></upload>
.

Controllers:

var controllers = {

  UploadCtrl: function ($scope) {

    $scope.images = [];
    $scope.files = [];

    $scope.upload = function (element) {
      $scope.$apply(function ($scope) {
        $scope.files = element.files;
      });
    };

    $scope.$watch('files', function () {

      for (var i = 0; i < $scope.files.length; i += 1) {

        var current = $scope.files[i];
        var reader = new FileReader();

        reader.onload = (function (file) {
          return function (env) {
            console.log(file.name);
            $scope.images.push({ name: file.name, src: env.target.result });
          }
        }(current));

        reader.readAsDataURL(current);
      }

    }, true);

  }

};

Directives:

var directives = {

  upload: function ($compile) {

    return {
      restrict: 'E',
      link: function (scope, element, attr) {
        scope.url = element.attr('url');
        element.html($compile(template)(scope));
      }
    };

  }

};

Template var (contains multi-line strings stored in a cs file)

template = """
<div ng-controller='UploadCtrl'>
  <input type='file' multiple onchange='angular.element(this).scope().upload(this)' />

  <div ng-repeat='image in images'>
{{image.name}}: <img ng-src='{{image.src}}' width='80' height='80' />
  </div>
</div>
"""

Answer №1

To ensure the images are updated, be sure to incorporate $apply into your code:

$scope.$apply(function () {
    $scope.images.push({ title: file.title, url: env.target.result });
}

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

Verifying the name's uniqueness and disregarding it in case of any alterations

I am currently working on a form that includes a modal to allow users to modify their name and email address. The issue I am facing is that the form sends a request to the server to check for unique values in all cases. While this is appropriate when creat ...

Time-driven occurrences in HTML

I want to create a daily event, like an alert box or a message displayed in a window, at 10 am on my webpage. How can I achieve this without constantly checking the time and wasting resources? ...

Discover the secret to automatically calling a function every minute when the page is loaded!

Our team is currently developing a PhoneGap application with 4 pages. We are in need of posting the current latitude and longitude every minute to our server. Fortunately, we are familiar with how to post values to the server as well as how to retrieve the ...

ReactJS and MaterialUI: Creating a Dynamic Triangle Button Slider

I am facing a challenge in creating a triangle-shaped button for a slider in Material UI and ReactJS, instead of the current pizza slice shape. Here is an example of the desired outcome: https://i.sstatic.net/pNn93.png Here is the current state of the sl ...

Generating a two-dimensional array and setting its values in JavaScript

I need assistance with creating and initializing a two-dimensional array in JavaScript within an AngularJS application. My current approach is as follows: $scope.invalidVote = []; for (var i = 0; i < $scope.arry1.length; i += 1) { $scope.answersCou ...

Modifying the color of an SVG in real-time and using it as a texture in Three.js

I have been attempting to develop a configurator using three.js, but I am currently stuck at the stage where I need to dynamically change the color of the product. My initial idea was to use an SVG as a texture, modify the fill property of the SVG, and eas ...

How can I extract the initial values from PHP after receiving the JSON + serialized data in the Ajax response following the first submission?

I am currently utilizing ajax to store data for multi part forms. My goal is to save each form's data upon clicking the next button. I have utilized form data to serialize the information, however, the format of the data is not aligning with my expect ...

Adding fresh information to a data entity

I'm currently in the process of updating a data object with a new value. Upon checking, if the data associated with event.data.id exists within $("#ArticlesHolder"), I proceed to update it as follows: if($("#ArticlesHolder").data(event.data.id) != n ...

Unable to reference the namespace 'ThemeDefinition' as a valid type within Vuetify

Looking to develop a unique theme for Vuetify v3.0.0-alpha.10 and I'm working with my vuetify.ts plugin file. import "@mdi/font/css/materialdesignicons.css"; import "vuetify/lib/styles/main.sass"; import { createVuetify, ThemeDefinition } from "v ...

Tips for setting up PhantomJS with Karma test runner

I've been attempting to run the karmatest runner with phantomJS on my Windows 7 machine. Here's the configuration file I'm using: // Karma configuration // http://karma-runner.github.io/0.12/config/configuration-file.html // Generated on 20 ...

Tips for implementing an element onClick change within a Redux container using React.js

After coming across a similar question by another user on this link, I found the answer quite clear. However, if you're dealing with a redux container, the states are transformed into props via the mapStateToProps function. So, my query is: how shoul ...

Having trouble parsing the JSON object values within the Error section of the Ajax call

When making an Ajax call to a rest web API, I encountered an error that I need help resolving. Here is the code snippet: $.ajax({ url: "/********/getbytitle('****')/items", type: "POST", contentType: "applicat ...

The array containing JSON objects enclosed within curly braces is causing a syntax error

Given a variable containing data that looks like an "array" with JSON Objects inside (even though it is not actually formatted as an array, starting and ending with curly braces): {"x1","x2"},{"y1","y2"},{"z1","z2"} How can I transform this so that the i ...

Step-by-step guide on incorporating a hyperlink within a row using @material-ui/data-grid

I am currently using @material-ui/data-grid to showcase some data on my webpage. Each row in the grid must have a link that leads to the next page when clicked. I have all the necessary data ready to be passed, however, I am facing difficulty in creating a ...

Is AngularJS Authentication Service Capable of Supporting Promises?

I have recently set up an authentication service that I inject into my Login controller. When I use it to perform a login, the process involves calling the service like this: $scope.login = function() { var loginResult = authentication.login($scope.m ...

Error encountered during Heroku deployment: "sh: 1: tailwind: not found"

package.json: "devDependencies": { "tailwindcss": "^0.7.4" }, "scripts": { "tailwind:css": "tailwind build src/css/tailwind.src.css -c tailwind.js -o src/css/tailwind.css", "start": "npm run tailwind:css && react-scripts start", ...

Ways to update a nested object by utilizing the setState method

I have a situation where I need to modify the key/value pairs of an object in my state. Specifically, I need to add a key/value pair to the object with an ID of 13. Please refer to the attached photo for reference. Although I know how to use setState, I ...

Creating diverse options using attribute-value pairs

I am in need of creating an array that contains all possible combinations of attribute values. Here is an example of my attributes/values object: let attr = { color: ['red', 'green', 'blue'], sizes: ['sm&apo ...

What is the best method for securing my API key within the script.js file while utilizing dotenv?

My goal is to conceal my API key using dotenv. Interestingly, when I replace require('dotenv').config(); with my actual API key in the code as apiKey: process.env.API_KEY, it works fine despite not using process.env.API_KEY. I made sure to inst ...

Selection dropdown not being populated by ng-options

After trying numerous examples to implement the changes, I am still facing issues. Even though I have an ng-model and clearly defined the object property I want to receive, it is not functioning as expected. Any assistance would be appreciated. Here is th ...