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

What is the best way to obtain an attribute name that is reminiscent of Function.name?

My objective is to securely type an attribute. For example, I have an object: const identity = { address: "Jackie" }; At some point, I will rename the address key to something else, like street_address. This is how it is currently implemented ...

Leveraging server-sent events (SSE) for real-time updates on a web client using JavaScript

I have been experimenting with server-side events (SSE) in JavaScript and Node.JS to send updates to a web client. To simplify things, I created a function that generates the current time every second: setTimeout(function time() { sendEvent('time&a ...

Is it possible to use both material-ui@next and the previous version concurrently?

I need some advice on a project I am working on that utilizes material-ui@next (v1). While I appreciate the new features in the latest autocomplete, I find it too complex for my needs. Instead, I would like to revert back to the older version of the autoco ...

Manipulating toggle buttons using CSS and jQuery

Check out this jsfiddle to see my attempt at creating a toggle switch in the form of a mute button. The toggle button shows the current setting: mute or unmute When hovered over, it displays the alternative setting However, I am encountering an issue wh ...

The value of req.body.stripeToken is not defined

I am facing an issue while using $http to post a form to my nodejs server. Upon posting, I attempt to retrieve the variable stripeToken using req.body.stripeToken in my server code, but it always returns undefined. Interestingly, when I make the post requ ...

Trouble with basic JavaScript functionality in a React component

Here is a unique component code snippet: import React, {Component} from 'react'; import 'D:/School/Alta/interactiveweb/src/webapp/src/App.css' class Chat extends Component { test() { alert(); } render() { return <nav ...

Tips for accessing elements other than the root element using this.$el

Within my template, the structure is as follows: <div v-show="showContent" class="content-block-body"> <div class="slider-pro"> <div class="sp-slides"> <slide v-for="block in subItems" ...

Troubleshooting issue with JavaScript sorting function failing to arrange elements in ascending

I'm having trouble sorting numbers in ascending order using JavaScript. Here's the code snippet: <h2>JavaScript Array Sort</h2> <p>Click the button to sort the array in ascending order.</p> <button onclick="myFunctio ...

The completion event was not triggered during the AJAX request

I am having an issue with a function that I have created to make an ajax call. Despite using the .done method, it does not seem to be firing as expected. Upon checking my console for errors, I came across the following message: function getIncidentInfo( ...

NodeJs Importing a File

Currently working with NodeJS, I have encountered a challenge. Is it possible to require a JavaScript file in Node similar to how we do in browsers? When using the require() method, I noticed that the JavaScript file called does not have access to global v ...

Implementing color transitions in javascript

Everyone talks about transitioning things in CSS, but have you ever thought about transitioning background colors in JavaScript? I'm currently working on a function that changes the background color of a div with the id of ex1 to green. However, I&apo ...

jQuery when - anticipate the fulfillment of multiple success/done callbacks

When using $.when to determine when an array of ajax promises are finished, I have noticed that although the ajax calls themselves are completed when $.when fires, their callbacks and done functions are not. How can I make sure to wait for the callbacks to ...

Is it possible to redirect a URL with a readyState of 4?

Is it possible to redirect to a page when the readyState is equal to 4? //load the send form if (sendRequest) { sendRequest.open("POST", urlRequest, true); sendRequest.setRequestHeader("Content-Type", "application/x-www-form-urlenc ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

Animating a JQuery Slider using code from scratch

I'm attempting to dynamically alter/animate a JQuery slider. In this scenario, there are two arrays present: one for the values that need to be modified and another for the durations between modifications. By monitoring the console, you'll observ ...

Learn the art of blurring elements upon clicking in Vue

I've been attempting to trigger the blur event on an element when it is clicked, but I haven't been able to locate any helpful examples online. My initial approach looked like this: <a @click="this.blur">Click Me</a> Unfortunately, ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

Can JSON be parsed using JavaScript?

Is it feasible to utilize JavaScript to parse information from an external URL hosting a JSON file on a different domain? The JSON data sample below shows various URLs with associated "q" values that I am interested in extracting. [{"url":"http://websit ...

Issue occurred when trying to load controllers during the migration process from AngularJS1 to Angular6

Currently, I am in the process of upgrading AngularJS1 components to Angular6. My strategy involves creating wrappers for all existing AngularJS1 components by extending "UpgradeComponent" and storing them under the folder "directive-wrappers". However, wh ...

"Using Sequelize's Op.and and Op.like operators led to an unexpected outcome of producing an empty

I am working on developing a search endpoint using express and sequelize. I noticed an issue where using Op.and in my 'where' object results in an empty object: const where = { [Op.and]: req.query.q.split(" ").map((q) => { ...