Unable to modify the model of the directive

I'm facing an issue where additional elements added to my array within a controller of a directive are not being displayed in the view. What's even more frustrating is that when I print my model, it doesn't reflect the new elements that have been added.

Let me show you how I've set up my directives:

angular.module('example',[]);

angular.module('example').directive('documentUpload', function() {

function link($scope, $element, attrs, ngModelCtrl) {
    $element.find('input[type="file"]').on('change', function (){
        $scope.submitFile(this);    
    });
}

return {
    restrict: 'E',
    templateUrl: 'document-upload.html',
    controller: function($scope,$element) {
        $scope.files = [{ name : "blah", src: "blah" }];
        $scope.submitFile = function(file,container) {
            var currentFile = file.files[0];
            var reader  = new FileReader();
            reader.onloadend = function(){
                $scope.files.push({
                    name: currentFile.name,
                    src : reader.result
                });
                console.log($scope.files);
                console.log($scope.example);
            }

            reader.readAsDataURL(currentFile);
        };
    },
    alias: 'document',
    link: link
}

}).directive('imageFiles', function($compile) {
    return {
        scope: {
            file: "="
        },
        template: '<img ng-model="file" ng-src="file.src" alt="file.name" class="img-responsive"/>'
    }
});

Despite my efforts, the updated model is still not displaying the latest element added:

<div class="row">
<pre>{{ files }}</pre>
<div class="col-lg-12">
    <form method="POST" enctype="multipart/form-data" ng-submit="submit(document)">
      <input type="file" name="file" ng-model="document./file/>           
    </form>
</div>
<div class="row" ng-repeat="file in files" image-files>

Feel free to check out this live example

Answer №1

Let me explain the current situation. When using reader.onloadend, which is an external function or plugin, there seems to be a missing link with the internal angular digest process.

In this scenario, it is essential to include $scope.$apply() after pushing to the array like so:

$scope.files.push({
   name: currentFile.name,
   src : reader.result
});
$scope.$apply();

By doing this, you prompt angular to refresh itself and update accordingly.

To ensure everything works smoothly, I have also provided a working example on Plunker:

http://plnkr.co/edit/xyz123ABCdeF45GHIjkl?p=preview

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

Issue with JQueryUI Dialog auto width not accounting for vertical scrollbar

My JQueryUI Dialog has the width property set to 'auto'. Everything functions properly except in situations where the content exceeds the height of the dialog: A vertical scrollbar appears, but it disrupts the layout of the content within the dia ...

What is the best tool to develop my AngularJs class library (service/factory/provider)?

I am currently working on my main service: (function (angular) { "use strict"; angular .module("app") .service("mainService", mainService); mainService.$inject = ["classLibrary"]; function mainService(classLibrary) { this.person = new clas ...

Using the input type 'number' will result in null values instead of characters

My goal is to validate a number input field using Angular2: <input type="number" class="form-control" name="foo" id="foo" [min]="0" [max]="42" [(ngModel)]="foo" formControlName="foo"> In Chrome, everything works perfectly because it ignores ...

Display a specific section depending on the user's input by utilizing either ng-if or ng-show

I have a scenario where I need to display one of two sections based on user input. If the user selects 'Daily' in the first 'type' input, I want section 1 to appear (Enter start date and hour). For any other type selection, I want secti ...

Using jQuery's deferred.done method to send an array of data to the done function

I followed the method outlined in https://api.jquery.com/jquery.when/ to execute a series of ajax calls (using the example $.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ) on that page). The code below is functional; however, I am struggling with ...

how to split a string by commas and convert it into an array using angularJS

I need to convert a string, like "12,13", into an array format such as [12,13] in my controller. Even after trying the split function, I couldn't get it to work properly. $scope.mySplit = function(string, nb) { var array = string.split(&ap ...

Mongoose is struggling to locate the expected result

I currently have three different schemas set up. User.js: const mongoose = require("mongoose"); const bcrypt = require("bcryptjs"); const userSchema = new mongoose.Schema({ name: { type: String, required: true, }, email: { type: String, ...

Is it Necessary for Bower to Update a Package Frequently?

I seem to be encountering an issue while attempting to build with gulp (highlighted as the first problem). I've observed that every time I run "bower update bootswatch," something is being downloaded. As I am not very familiar with package management, ...

AngularJS in Action: Communicating Between Services, Controllers, and Directives

There is a situation where some menu items are enabled while others are disabled in the user interface. When a user clicks on a disabled menu item, an error is displayed on the page. To address this issue, I attempted to use AngularJS service and $broadca ...

summing up the initial elements from every array generated dynamically

My data is structured as follows: { "questions": ["Variety of food options", "Food quality", "Freshness of food"], "countries": ["Netherlands", "Belgium", "France"], "values": [ [ [5, 88, 18], [50, 83, 10], ...

Struggling with dragging Vue.js modals?

I am currently utilizing the vue-js-modal library, and I'm encountering an issue with it. Whenever I set my modal to be draggable by using :draggable="true", I can drag it around but then I am unable to input any text in the form fields. It seems to c ...

Guide on how to retrieve server error responses in javascript using axios

I am currently using axios to send form data to a Laravel backend. While I can easily access the response upon success, I am facing difficulties retrieving the error response. In my browser's developer tools, under network > response, I see the fo ...

Parcel Bundler works perfectly fine on localhost, however, an error is being displayed on the index.html file in the Dist folder

Currently, I am in the process of learning how to use Parcel for bundling purposes. I have set up a index.html file that is connected with index.js. Surprisingly, everything works perfectly fine when I access it via localhost:1234 using Parcel. However, wh ...

When processing a response from the backend (using express js), cookies are not being received in the browser while on localhost

I'm currently facing some difficulties with implementing authorization cookies within my application. Whenever I attempt to send a GET request to my API (which is hosted on port 8080) from my React frontend (running on port 3000), the cookies that I ...

A guide to customizing the appearance of Textfield labels in Material-UI using React

Can someone assist me with changing the label color in Material-UI from grey to black? I am new to Material-UI and struggling to figure it out. Below is the code snippet: import React from "react"; import ReactDOM from "react-dom"; import { TextField, Bu ...

How can I conceal the element that came before in JavaScript?

<div onclick="toggleContent(this)" class="iptv"><div class="triangle"></div><b>LUZ HD</b> - 98 channels (including 32 HD channels) <div class="iptv_price"><b><img src="img/rj45.png" class="icon_ofert ...

The issue with Nextjs getStaticPaths is that it is not retrieving data from Firebase Firestore

I'm encountering an issue with fetching dynamic data from firestore in nextjs using getStaticPaths. While rendering the data from firestore with getStaticProps works, I'm facing a problem when trying to access specific item details as it leads me ...

How can you target a specific data-target button while working with multiple Bootstrap collapse elements?

One challenge I'm facing is with the Bootstrap collapse elements on my website. I have several of them, each controlled by a read-more button that includes an icon to indicate the state of the collapse element. However, when I add a class to the butto ...

What is the appropriate way to utilize `render_template` from Flask within Angular?

I'm facing an issue where I need to implement different routes for various Angular Material tabs. I have attempted to directly call Flask from the template, as demonstrated below, but unfortunately, I am unable to invoke render_template from Angular. ...

Discover the simple steps for automatically scrolling to a specific div using AngularJS

I want the error message div to appear when I click on the submit button and I also want the screen to automatically scroll to that div. Below are my code snippets: CSS:- .error_msg { background: none repeat scroll 0 0 #F16200; border: 0 solid # ...