Incorporating a single button for custom upload and submission using AngularJS

I have been searching for a solution similar to this in angular without much success. What I discovered is that I need to somehow use the "onchange" method in my code:

   <form ng-controller="uploadCtrl as up" name="up.upload_form">
       <div class="fileUpload btn btn-primary">
                    <span>Upload</span>
                    <input type="file" class="upload"
                           ngf-select
                           ng-model="up.file"
                           name="file"
                           ngf-max-size="20MB"/></div>
     <button type="submit" class="btn btn-default" ng-click="up.submit()">Upload</button>
   <i ng-show="up.upload_form.file.$error.required">*required</i><br>
   <i ng-show="up.upload_form.file.$error.maxSize">File too large
      {{up.file.size / 1000000|number:1}}MB: max 20M</i>
   <button class="btn btn-default"  ng-click="compare_it()">Compare it</button>
                    <pre>{{up.progress}}</pre>
 </form>

This represents my controller

app.controller('uploadCtrl',['Upload','$window',function(Upload,$window){
    var vm = this;
    vm.submit = function(){ //function to call on form submit
        if (vm.upload_form.file.$valid && vm.file) {//check if from is valid

            //console.log(vm.file.name);
            vm.upload(vm.file); //call upload function
            //vm.file.name = prompt("put you name");
        }
    };

    vm.upload = function (file) {
        Upload.upload({
            url: '/upload', //webAPI exposed to upload the file
            data:{file:file} //pass file as data, should be user ng-model
        }).then(function (resp) { //upload function returns a promise
            if(resp.data.error_code === 0){ //validate success
                $window.alert('Success ' + resp.config.data.file.name + ' uploaded.');
            } else {
                $window.alert('an error occured');
            }
        }, function (resp) { //catch error
            console.log('Error status: ' + resp.status);
            $window.alert('Error status: ' + resp.status);
        }, function (evt) {
            console.log(evt);
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
            vm.progress = 'progress: ' + progressPercentage + '% '; // capture upload progress
        });
    };
}]);

Is there any way to combine the input type="file" and button type="submit"? Any assistance would be greatly appreciated.

Answer №1

Within the controlling module:

$scope.$watch("up.file", function() { if (up.file) up.submit() });

Alternatively, in the user interface:

<input type="file" class="upload"
                       ngf-select
                       ng-model="up.file"
                       ng-change="up.submit()"
                       name="file"
                       ngf-max-size="20MB"/>

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

Puzzling array challenge. Lack of clarity in explanation

I am currently working on a series of JavaScript tests available at js-assessment One of the tasks states: it("you should be able to find all occurrences of an item in an array", function() { var result = answers.findAllOccurrences('abcdefab ...

Accessing information from an Angular Elements Web Component using vanilla JavaScript

I am in the process of creating several WebComponents that I plan to utilize across various libraries and frameworks, with a primary focus on plain vanilla JavaScript. My current consideration is to implement Angular Elements for this purpose, and I have a ...

What is the best way to assign the variable using Firebase data?

Having trouble setting a variable with data retrieved using a get() function on Firebase. export default { name: "customer-navigation", mixins: [navigationMixin], components:{AppSnackBar, authModule,AuthForm}, data () { return { drawer: fa ...

Prevent tracking of campaigns in Google Analytics by not following tagged links from banners to a website

My website is connected to Google Analytics. I have banners on my site that link to external pages with tracking tags added to the URL: However, I am not seeing campaign statistics in the Traffic Sources - Campaigns section of my Google Analytics account. ...

What are some effective ways to utilize the outcome of a FB FQL multiquery?

I'm having some confusion with Facebook's fql.multiquery feature. My goal is to fetch all the comments on a specific post and then retrieve the user information for each commenter. While I can easily get the comments, I am facing difficulty in o ...

Adding values to an array with the click of a submit button in React JS

I have a unique challenge with creating a form that includes custom inputs. const Input = (props) => { return ( <div> <label className={classes.label}>{props.label} <input className={classes.input} {... ...

javascript create smooth transitions when navigating between different pages

As a newcomer to JS, I am currently working on creating a website with an introduction animation. My goal is to have this animation displayed on a separate page and once it reaches the end, automatically redirect to the next webpage. <body onload="setT ...

Is my Magento journey on the correct course?

I am wanting to include or require a file in DATA.php within magento. Below is the code snippet I have: public function formatPrice($price) { require_once(Mage::getBaseDir('app').'\design\frontend\neighborhood ...

Leveraging the power of Restangular by utilizing a complete URL

Restangular for AngularJS has a lot of useful functions, but one issue I have is the inability to easily pass a full URL to it. While I understand the advantages of using .one('something','someparam'), my problem lies in having to split ...

Keeping JSP current with changes made to files on the client side

Currently, I am tackling a project that consists of two main components: a) A Java Application that runs on a client machine. b) A Web Application that is hosted on a web server. The Java Application generates results at random intervals. These results n ...

What steps should I take to troubleshoot the 'TypeError: userId is not a function' error in my unban feature?

I am currently working on implementing an unban feature for my bot, however, I am encountering issues whenever I try to test the command (!unban <userId>). Instead of the expected outcome, I am faced with an error which is detailed below. This snipp ...

Creating a progress bar feature using local storage in JavaScript

Is there a way to retain the progress of the countdown timer with a progress bar on page reload? Here is an example of what I am trying to achieve: https://codepen.io/Rudchyk/pen/qNOEGj <div id="progressBar"> <div class=& ...

Comparing the Length of JavaScript Arrays

I have code that checks for similar values in two arrays, and if there are any, they are not displayed in the result. However, when I switch the lengths of the arrays so that Array2 is longer than Array1, I end up with an empty result array. How can I achi ...

How to Implement Custom Header in AngularJs during Initialization

Let's say I have a delicious Angular application called chococalateApp that relies on 3 other modules: Product, Sales, and LogIn. My app is based on a RESTful API. After a successful login, the server sends an authentication token that needs to be ap ...

What could be the reason behind the failure of Google Place API integration?

When I try to access the JSON data from the provided link, it works fine. However, when I integrate it into our project, there seems to be an issue. Link to JSON Data ...

Troubleshooting Date Format Issue in AngularJS Input Component

I am facing an issue with a view that displays records and allows them to be edited by clicking 'edit' at the end of each row. While the records display correctly in 'display' mode, the date field is not populated when switching to edit ...

I am facing an issue where the group-hover feature does not seem to be functioning properly

My NextJS app seems to be having trouble with group-hover functionality. I've experimented with different ways of declaring group-hover at various levels, but it doesn't seem to be working properly. Interestingly, when I changed group-hover to ...

Is it possible to reuse a variable within a single HTML tag when using Angular 2?

I encountered a strange issue with Angular 2 that may be a bug. I noticed that I couldn't print the same variable in a template twice within the same HTML tag. When I tried to use the following code, it resulted in error messages. <div class=" ...

Retrieve data visualization tools from a separate function

Below is a Google dashboard featuring filtering, sorting, and paging functionality. I need to programmatically modify the sourceData and refresh the Google visualization from outside its containing function. The challenge is accessing the visualization fr ...

Can Chrome Support Bookmarklets?

While attempting to craft a bookmarklet in Chrome using the console, I encountered the following error: Refused to load the script 'https://code.jquery.com/jquery-1.6.1.min.js' because it violates the following Content Security Policy directive: ...