Trigger a function when the value of the file input field changes using ng-change

I'm attempting to trigger my upload() function when the file input changes, but I'm having trouble getting it to work.

This is the HTML code:

<input type="file" ng-model="image" ng-change="uploadImage()">

And here's the corresponding JavaScript code:

$scope.uploadImage = function() {
    console.log('Changed');
}

Can anyone spot what mistake I might be making?

Answer №1

Give this a shot:- http://jsfiddle.net/adiioo7/fA969/

JavaScript Code:-

function myFunction($scope) {
    $scope.uploadFile = function () {
        console.log("Updated");
    }
}

HTML Markup:-

<div ng-app ng-controller="myFunction">
    <input type="file" ng-model="file" onchange="angular.element(this).scope().uploadFile()" />
</div>

Answer №2

If you're looking for a solution that works in production mode, I've created a directive that can help with your file upload needs. Here's how you can use it:

<input ng-upload-change="fileChanged($event)" />

In your controller:

$scope.fileChanged = function($event){
    var files = $event.target.files;
}

Don't forget to include the directive in your code:

angular.module("YOUR_APP_NAME").directive("ngUploadChange",function(){
    return{
        scope:{
            ngUploadChange:"&"
        },
        link:function($scope, $element, $attrs){
            $element.on("change",function(event){
                $scope.$apply(function(){
                    $scope.ngUploadChange({$event: event})
                })
            })
            $scope.$on("$destroy",function(){
                $element.off();
            });
        }
    }
});

No need for attributions - this code is in the public domain.

Just keep in mind that if a user selects a file, closes the input, and then selects the same file again, the change function won't trigger. To address this issue, I've developed a more comprehensive directive that replaces the input each time it's used. You can find it on github here:

https://github.com/dtruel/angular-file-input/tree/master

Answer №3

If you're looking for an alternative method to detect changes in file input, one interesting approach is to use a watch on the ng-model attribute of the input file.

Here's an example:

HTML ->

<input type="file" file-model="change.fnEvidence">

JS Code ->

$scope.$watch('change.fnEvidence', function() {
                    alert("has changed");
                });

I hope you find this useful.

Answer №4

Make sure to utilize ng-file-select="upload($files)" for file selection.

'<input type="file" class="form-control" ng-model="alunos.file" accept="image/*" ng-file-select="upload($files)"/>'

To define the upload function, use:

$scope.upload = function(file){
    console.log(file);
};

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 method for selecting only files (excluding folders) in Gulp?

I have a gulpfile where I am injecting files into an appcache manifest in this manner: var cachedFiles = gulp.src('**', {read: false, cwd: 'build'}); gulp.src('src/*.appcache', {base: 'src'}) .pipe($.inject(cachedF ...

The troubleshooting of debugging javascript remotely on IntelliJ with the JetBrains Chrome extension is proving to be unsuccessful

I've been attempting to set up a debugger for some JavaScript files that I'm working on in IntelliJ (version 2020.1.4). Following the guidelines provided here Debug with JetBrains Chrome extension, I believe I have successfully completed all the ...

Tips for hiding the bottom bar within a stackNavigator in react-navigation

I am facing a challenge with my navigation setup. I have a simple createBottomTabNavigator where one of the tabs is a createStackNavigator. Within this stack, I have a screen that I want to overlap the tab bar. I attempted to use tabBarVisible: false on th ...

How can I switch to another screen from the menu located within my Parent Component?

I've been working on adding a customized navigation menu to my react-native app, but I'm currently facing the challenge of not being able to navigate to the corresponding screens of the selected menu items. I tried using this.props.navigation.nav ...

Disabling the movement of arrows in the client-testimonials-carousel plugin

This plugin that I'm currently using is working flawlessly: However, I'm unsure about how to make the arrows stationary and prevent them from moving. Currently, they are centering themselves based on the height of the div, but I want them to rem ...

When a JSON object is handled as a string

The JSON returned from my Ajax call looks like this: returnedData = "[ { id: 1, firstName: 'John', lastName: 'Smith', address: '123 Spa Road', city: 'London', orders: [ { product: ...

You do not have the authorization to access this content

I have been working on a Laravel web application to upload images into a data table and allow users to download the uploaded image on click. Initially, everything was working fine until I made changes in the code from return '{!! Html::link('ima ...

Generate a dynamic HTML table using an array of objects

I have a dataset that I need to transform into an HTML table like the one shown in this image: https://i.sstatic.net/gRxJz.png Despite my attempts to write the code below, it seems that the rows are being appended in different positions. Is there another ...

js issue with passing form data to use with PHP mail function

As a novice, I am diving into the world of HTML webpage creation. Utilizing a free online template, my current project involves developing a Contact Page that triggers a php script to send an email with the captured fields. While I've successfully man ...

Best practices for implementing JavaScript in JSP pages

After researching various sources, I have come across conflicting opinions on the topic which has left me feeling a bit confused. As someone new to web programming using java EE, I am looking to integrate javascript functions into my code. It appears that ...

What is the best way to implement form fields that have varying validation patterns based on different conditions?

Currently, my focus is on developing a form that prompts the user to choose between "USA" or "International" via radio buttons. The input field for telephone numbers should then adapt its requirements based on the selected country - either a 10-digit US nu ...

Choosing a subset of data within a JavaScript object with the help of jQuery/jHashtable

Here is an object that I am working with: var data = { "info" : [{ "title": "Desemberkonsert", "description": "MangerFHS 09/10" }], "playlist" : [ { "title": "In This Place", "description": "Excalibur", "href": "desemberkonsert_in-this-place", "url": "flv ...

Loop through each HTML element and store it in a JavaScript array

I currently have a webpage with 3 select buttons named "Season". I am trying to figure out which buttons are selected and receive their values as an array on my webpage. Below is the code I am using: var season_array = $.each($(form).children("input.sele ...

Is there a way to automatically close all open sub-menus when clicking on a different parent menu item?

Check out this LINK for the code I am using. When I click on the Parent Menu, such as Services, the sub-menu of the Services menu will open. However, when I click on another menu, the sub-menu will also open. I want the previous sub-menu to close when I c ...

Automatically focus on new page when button is clicked (in a separate HTML file)

I successfully added auto-focus functionality to a button that opens a modal using the code below: Created with AngularJS: app.directive('autoFocus', function($timeout) { return { restrict: 'AC', link: function(_sc ...

There was an error during compilation: Module not detected - Unable to locate './xxxx'

Looking for help with importing a file from another folder into my Next.js project. I need assistance with the correct syntax and paths as I am encountering an error. Here is a link to the screenshot of the error: https://i.sstatic.net/jZ6kk.png Below are ...

Use multiple lines to create a stunning visualization using morris.js. Let your data

I need help creating a graph using morris.js with 2 lines. I have two sets of data in one array, but I can't seem to display both lines on the graph simultaneously. When I use todos[0], only the first line is visible, and when I use todos[1], only the ...

locate handlers for events using selenium web automation

Recently, I began exploring Selenium. Can Selenium locate event handlers connected to an HTML element? These handlers, such as onclick for a button, may be dynamically added using addEventListener. ...

The 'otherwise' controller in AngularJS does not execute when the resolution in another controller has not been successful

Imagine having routes set up in the configuration: $routeProvider .when('/person/:person_id', { controller: 'person', templateUrl: 'partials/person.html', resolve: { data: ['api', '$route', ...

Leverage AJAX on the client-side for optimal performance while utilizing node.js

I am currently working on a simple nodejs application that displays HTML pages. Within this application, there are two buttons that are linked to JavaScript functions in separate files. One of the functions uses ajax, while the other does not. However, I a ...