Firing ng-change with fileModel or input type="file"

Is there a way to trigger ng-change when a change occurs with this file directive?

I have implemented a custom file directive for this purpose.

The Directive:

app.directive('ngFileModel', ['$parse', function($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.ngFileModel);
            var isMultiple = attrs.multiple;
            var modelSetter = model.assign;
            element.bind('change', function() {
                var values = [];
                angular.forEach(element[0].files, function(item) {
                    var value = {
                        // File Name 
                        name: item.name,
                        //File Size 
                        size: item.size,
                        //File URL to view 
                        url: URL.createObjectURL(item),
                        // File Input Value 
                        _file: item
                    };
                    values.push(value);
                });
                scope.$apply(function() {
                    if (isMultiple) {
                        modelSetter(scope, values);
                    } else {
                        modelSetter(scope, values[0]);
                    }
                });
            });
        }
    };
}]);

Any suggestions on how to implement ng-change without utilizing ng-model?

The HTML:

 <input type="file" name="" ng-file-model="uploadThisImage" ng-change="onFileSelect($index)">

Answer №1

Creating a Custom Directive for File Input in AngularJS

This special directive allows the <input type=file> element to seamlessly integrate with the ng-change and ng-form directives.

By default, AngularJS's built-in <input> directive does not support handling <input type=file>. To enable this functionality, a custom directive must be implemented.

<input type="file" files-input ng-model="fileArray"
       ng-change="onFileSelect()" multiple />

The files-input directive is defined as follows:

angular.module("app").directive("filesInput", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
})

This directive sets up a listener for changes that updates the model with the selected files from the input element.

Check out the DEMO on PLNKR


Interactive Example of files-input Directive

angular.module("app",[]);

angular.module("app").directive("filesInput", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    
    <input type="file" files-input ng-model="fileArray" multiple>
    
    <h2>Selected Files</h2>
    <div ng-repeat="file in fileArray">
      {{file.name}}
    </div>
  </body>

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

Tips on implementing a jQuery .load() function using an anchor tag within dynamic content

I am working on a search page where user input is taken from a form and then sent to a PHP file that makes a cURL call to an external server. The PHP file receives an array from the server, which it uses to display HTML in a "results" div on the original s ...

What are the steps to troubleshoot a Node Package Manager library in Visual Studio Code?

I have created a Typescript library that I plan to use in various NodeJS projects. The source code is included in the NPM package, so when I install it in my projects, the source also gets added to the node_modules folder. Now, during debugging, I want to ...

Updating choices within a div in real-time by changing the select box dynamically

I need to swap out the select box that is nested inside this div <div class="models"> <select disabled="disable"> <option>Model Name</option> </select> </div> I am attempting to target the div and manipul ...

What's the best way to refresh append() functionality within a modal? I'm currently working with NODE JS and AJAX and

Whenever I click the modal, the append() calls are adding HTML content. But if I try to use empty() or html(), the modal stops appearing altogether. What is the correct approach to creating this modal? function loadModalContent(id) { $('#myModal& ...

Clear the Material-UI textfield upon form submission

After submitting the form, how can I clear the value from the TextField? All of the components in my code are functional components, not class ones. The example below shows one of the TextFields, with others similar to it. Currently, setting type='sea ...

Dynamically insert letters into each row as the HTML table increases

How can I display dynamically increasing alphabets in a newly generated cell on the left side of each row, based on the option selected in a dropdown list? These alphabets will serve as bullet points or serial numbers for the text boxes in each row. View ...

How can we manage JSON data in chunks during a progress event?

My dilemma involves dealing with a server request that may bring back a substantial JSON list (around 100K records, approximately 50 Mb) of points to be presented on a canvas using D3js. To ensure interactivity and save memory, I am keen on rendering them ...

What causes the form to be submitted when the text input is changed?

I'm puzzled by the behavior of this code snippet that triggers form submission when the input value changes: <form> <input type="text" onchange="submit();"> </form> Typically, I would expect something along t ...

The Jquery ajax get method is malfunctioning

I've been trying out this code but it doesn't seem to be working. Apologies for the basic question, but I'm curious to understand why it's not functioning as expected. $(document).ready(function(){ $("button").click(function(){ ...

Make a request to the local API in a React Native mobile app by sending a GET request

Currently, I am working on a mobile application using React Native and utilizing SQL Server and NodeJS. The API for this project is located in my localhost. Upon running the application on an emulator, I encountered an issue when attempting to make a reque ...

Storing a Promise in a Variable in React

As a newcomer to JavaScript/React, I am finding it challenging to grasp the concept of using Promise and async. To illustrate, consider the API call getSimById in a JS file that returns a Promise: export function getSimById(simId) { return fetch(simsUrl ...

Set up specific vue.config.js configurations for unique environments in Vue

I am working on a multi-page app where I want certain pages to only show up in my development environment. Here's how my vue.config.js looks: module.exports = { productionSourceMap: false, pages: { index: "src/main.js", admin: { ...

Is it possible to update the version of NPM?

Having an issue with installing packages for my React-Native project due to a NPM version error. How can I upgrade it? Currently using version 4 ...

The JavaScript confirm function will provide a false return value

Is it necessary to display a confirmation message asking "Are you sure ..."? I have implemented the message, but the function return false; is not working when the user clicks NO. <script> function confirmDelete(){ var answer = confirm("Are you su ...

Having trouble getting Fullcalendar to show up on my cordova app

Currently, I am in the process of building a mobile application using ionic and cordova. My goal is to incorporate a timetable system utilizing Fullcalendar and a PHP page that showcases MySQL data in JSON format. Despite my efforts, I am encountering diff ...

Is there a way to locate a parent class starting from a child class, and subsequently track down another child class from the parent?

I am facing a challenge with multiple tags structured like this: <div class="A"> <div class="B1">...</div> <div class="C1">Hello World!</div> <div class="C2">World Hell ...

Add a preventDefault event listener to a submit button that triggers a specific function

$(function() { $('#login').submit(function(e){ preventSubmission(); e.preventDefault(); }); }); function preventSubmission() { $('#btnLogin').attr('disabled','disabled'); $("#btnLogi ...

Customized function enabling dynamic menu display based on varying screen dimensions

Looking for assistance with JS and jQuery as I am relatively new to it. Any help would be greatly appreciated... I'm currently working on a responsive header where I want to implement onclick functions for mobile and tablet resolutions only. I' ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

Rhino's env.js causes the anchor element's pathname to be undefined

Encountered an issue that appears to be related to how anchor tags are implemented in Rhino. Despite using env.js, there might be a configuration error causing the problem. The issue arises when writing unit tests for code designed for an angularjs applic ...