Issue with Angular directive not updating model

Hey there, I've been struggling to update my model using a directive but for some reason it's not working. I'm having trouble figuring out why. Can anyone lend a hand?

Here is the HTML code snippet:

<input type="file" name="documents" file-model ng-model="documents" multiple>
<button class="btn btn-xs btn-default" ng-click="loadDocuments()">

And here is the directive in question:

app.directive("fileModel", ["$parse",function ($parse) {
    return {
        restrict: "A",
        require:"ngModel",
        scope: {
            ngModel: '='
        },
        link: function (scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;
            element.bind("change", function () {
                scope.$apply(function () {
                    scope.ngModel = element[0].files;
                });
            });
        }
    };
}]);

This is what I'm getting as output:

$scope.documents={};
$scope.loadDocuments = function () {
        console.log($scope.documents); //PRINT UNDEFINED
    }

Answer №1

Check out this code snippet:

app.directive("fileModel", ["$parse",function ($parse) {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;
            element.bind("change", function () {
                scope.$apply(function () {
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

<input type="file" name="photos" file-model="photos" multiple>

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

Discovering ways to monitor Service Providers

What Currently in my AngularJS project, I am attempting to monitor certain internal functions such as angular.module and serviceProvider. How Fortunately, I have managed to keep track of calls to angular.module successfully. var moduleCalls = spyOn(an ...

Tips on stopping slideToggle from opening and closing when clicked for the first time

When using the slideToggle function, I'm encountering an issue where the content div briefly shows on the first click but then immediately slides closed. Subsequent clicks work as expected and slide open correctly. This is the Jquery script I have be ...

Utilizing Angular and Cordova within a Virtual Directory

In an Angular application running in a virtual directory (https://{url}/{virtualDirectory}), I am attempting to encapsulate it within a Cordova application that references the same URL as the content source (<content src="https://{url}/{virtualDire ...

The challenge of vertically aligning text in a dynamically generated div

Currently, I am in the process of developing a straightforward application that allows for the dynamic addition of students and teachers. I am dynamically adding divs with a click function. To these dynamically created divs, I have assigned the class "us ...

Permanently removing artwork from the Canvas

I am facing an issue with my canvas drawing function. Whenever I clear the drawings on the background image by clicking a button, the old drawings reappear when I try to draw again. How can I permanently delete the cleared drawings so that I can start fr ...

Seeking a POST request to a specific URL

Hey there! I'm currently working on developing an Airtime application and need some guidance. Here's what I need help with: To send airtime, I have to make a HTTP POST request to one of the following endpoints: Live: Sandbox: These are the req ...

Boosting Performance in Three.js - Achieving a Faster Frame Rate

Utilizing Three.js alongside Nvidia's 3D Vision shutter technology has been an interesting experience for me. In my rendering process, I have implemented the following steps: // Setting up the 3D Vision Camera (Shutter Glasses) var eye_separation = 0 ...

Return to a mention of a tree reference

Here is an example code snippet: <table> <tr> <td></td> <td></td> <td> <table> <tr> <td><a href="#" class="fav">click me</a></td> ...

Several different factors

I need to develop a form that allows users to edit existing comments. The form will display a textarea containing the old comment text and a submit button. My goal is to send the newComment data via ajax to another script. However, I am facing an issue w ...

Creating a custom Shape Geometry that is derived from BoxBufferGeometry

Looking to create a ShapeGeometry that can be defined by a list of points representing the shape boundary or faces, along with a corresponding list of textures for each face. While the BoxBufferGeometry class provides a starting point, I am in need of guid ...

Encountering issues when integrating AngularUI with Bootstrap 3 wiring

I've been struggling to integrate AngularUI with Bootstrap 3 without success. I copied the necessary AngularUI code from the bootstrap 3 branch found here: https://github.com/angular-ui/bootstrap/tree/bootstrap3_bis2 For my first attempt, I decided t ...

Encountered an $injector:unpr error while attempting to inject ui-calendar into my controller

I'm currently integrating ui-calendar into my project. The calendar will display different views based on the database values in various pages. To streamline the process of calling the calendar function multiple times, I decided to encapsulate the cod ...

The method to utilize JavaScript for capturing an HTML document along with its values

I am facing a challenge with a dynamic page that contains several input fields, select menus, and checkboxes. My goal is to save the entire page with all its content into a variable, including text entered and menu selections made. While document.getEleme ...

JavaScript: Cloning an array using the filter method

I have come to realize that there is no definitive best practice for copying an Array in Javascript. Is it a viable option to utilize Array.filter to copy an Array? For example: var words = ['spray', 'limit', 'elite', &apos ...

AngularJS, Implement a "read more" feature after a specified number of characters

Is there a way to implement a "read more" tag in Angular that will automatically appear if a string exceeds 100 characters? I've been searching for an example without any success. Any help would be appreciated. Edit: -- SUCCESS! Thanks to Don' ...

Issue with Framer Motion Modal: Animation presence fails to function

Currently, I am facing an issue with the exit animation of a modal created using framer motion. While the initial animation on opening the modal works perfectly fine, the exit animation fails to trigger and the modal disappears abruptly without any transit ...

Having trouble with a Three.JS/WebGL 3D object not loading in Firefox?

After creating a 3D Object using Three.js examples, I noticed that it works perfectly in Chrome and IE 11, but for some reason, it's not loading on Firefox. I am currently using the latest version of Firefox (FF 27.0). When I tested the code on Firef ...

Executing a function within the link from a controller in an angular directive with Angular JS

I recently developed a custom directive that includes both a link and controller. Here is the code snippet: var delightMeterApp = angular.module('delightMeterApp', []); delightMeterApp.directive('delightMeter', function () { ...

Using AJAX to retrieve HTML elements may cause compatibility issues with Jquery

I am facing an issue with my unordered list implementation. Initially, the list is empty: <ul id="showlist"></ul> When the user triggers an AJAX function, the list gets populated like this: <ul> <li>a</li> <li> ...

Trigger a function upon window reload with the click of a single button

$('#start').click(function () { window.location.href=window.location.href; runme(); }); I have a simple goal: whenever the user clicks the start button, I want the page to reload while still executing the custom rume function. Is there a w ...