Showing a specific document from an <input> field using AngularJS

I currently have a functional example using standard Javascript, but I am eager to enhance its compatibility with AngularJS.

My main objective is to dynamically update the span element with the filename of the file chosen by the user.

Below is the code snippet that I have implemented using native Javascript:

<span>
    <input  ng-model="uploadDownloads" type="file" style="visibility:hidden; width: 1px;" id=uploadDownloads name=uploadDownloads onchange="$(this).parent().find('span').html($(this).val().replace('C:\\fakepath\\', ''))"  /> <!-- Chrome security returns 'C:\fakepath\'  -->
    <input  class="btn btn-primary" type="button" value="choose file" onclick="$(this).parent().find('input[type=file]').click();"/> <!-- on button click fire the file click event -->
    <span  class="badge badge-important" ></span>
</span> 

I have already implemented the filereader function in AngularJS:

$scope.add = function(valid){
        if(valid){
                $scope.data = 'none';
                var f = document.getElementById('uploadDownloads').files[0];
                var r = new FileReader();
                r.onloadend = function(e){
                    $scope.data = e.target.result;
                    $scope.notPass = false;
                    $modalInstance.close({
                        'data':$scope.data,
                        'fileName':$scope.fileName,
                        'fileExplain':$scope.fileExplain
                    });
                };
            /*activate the onloadend to catch the file*/
                r.readAsBinaryString(f);
        } else {
            $scope.notPass = true;
        }
    };

However, I am facing a challenge in triggering the onclick and onchange events in AngularJS instead of regular JavaScript to update my <span> element with the selected filename.

Answer №1

This question is an extension of a previous question and answer. However, I have made modifications to the code provided in that answer to suit the specific requirements of this question, which involve updating a <span> element with the filename selected by a user in a way that aligns with AngularJS practices.

For a demonstration, you can view a sample on codepen.

Below is the relevant segment of the HTML file:

<body ng-controller="AppController">
    <input ng-model="uploadDownloads" type="file" fd-input file-name="fileName"/> 
    <span class="badge badge-important">Output here: {{fileName}}</span>
</body>

The crucial element here is the custom directive called fd-input, which establishes a two-way binding with an attribute named

file-name</code. By assigning one of your <code>$scope
variables to this attribute, the directive will automatically bind the selected filename to it. Here are the controller and directive implementations.

(function() {
  'use strict';

  angular.module('app', [])
    .controller('AppController', AppController)
    .directive('fdInput', fdInput);

  function AppController($scope) {
    $scope.fileName = '';
  }

  function fdInput() {
    return {
      scope: {
        fileName: '='
      },
      link: function(scope, element, attrs) {
        element.on('change', function(evt) {
          var files = evt.target.files;
          console.log(files[0].name);
          console.log(files[0].size);

          scope.fileName = files[0].name;
          scope.$apply();
        });
      }
    }
  };

})();

As mentioned earlier, the directive is adapted from a solution provided in another SO answer. I have enhanced it by introducing a scope for a two-way binding with a file-name attribute:

...
return {
  scope: {
    fileName: '='
  },
...

The selected filename is then assigned to the two-way binding:

...
scope.fileName = files[0].name;
scope.$apply();
...

Feel free to explore the codepen for a practical demonstration. Avoid relying on the parent scope within the directive, as it may restrict the directive to be used only once per controller. Moreover, if you intend to handle multiple files, you will need to upgrade the code to support an array of files instead.

I hope this explanation proves beneficial.

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

Scrolling to an id element in Vue.js can be achieved by passing the ID in the URL using the "?" parameter. This

My challenge involves a URL http://localhost:8080/?london that needs to load directly to the element with an id of london in the HTML section <section id="london"> on the page. Using http://localhost:8080/#london is not an option, even though it woul ...

What is the most effective way to ensure that a child component only executes when a link is clicked on the Vue component?

There are two components in my code The first component, which is the parent component, looks like this : <template> <ul class="list-group"> <li v-for="item in invoices" class="list-group-item"> <div class="ro ...

Sending information using AJAX to interact with a PHP script

My input field is set up to receive multiple files: <input id="propertyImages" type="file" name="submission_img[]" multiple accept=".jpg, .jpeg, .png, .gif"/> Afterwards, I send this data via JS/Ajax to a PHP file: //Creating the form data to be s ...

How can HTML5 geolocation be utilized to provide real-time latitude and longitude coordinates for integration with the Google Maps API?

I am currently working on a project where I need to dynamically fetch longitude and latitude values from the browser geolocation and then include them in the options array for the Google Maps API. Here is the code snippet I am using: function initMap(){ ...

Utilizing JavaScript or jQuery to adjust the cursor pointer value based on user input

Issue: Need help with live updating of input value to range input pointer [Check out my CodePen for reference][1] Adjust upper range input pointer based on lower range input pointer ][2] I am currently working on a range-to-range calculator for a book ...

Trying to extract data from the ASX website's table using web scraping techniques

My goal is to extract the current stock value from the ASX.com.au website. Specifically, I am interested in retrieving the current ASX value, which can be located here. The value I am looking for is in the second td from the left, currently standing at 30 ...

Information vanishes as the element undergoes modifications

I am currently working with a JSON file that contains information about various events, which I am displaying on a calendar. Whenever an event is scheduled for a particular day, I dynamically add a div element to indicate the presence of an event on the c ...

Creating a Google Captcha with validation is a straightforward process that can enhance the

I am having issues with adding Google Captcha to my form. Despite all fields working properly, the Captcha integration seems to be causing some disruptions. I have included my code below. Thank you in advance for your help. Please also check the following ...

Modifying the CSS class of an element does not produce the desired effect after altering its styles using JavaScript

html: <input id="myinput" class="cinput" type="image" src="http://www.foodwater.org.au/images/triple-spiral-3-small-button.jpg"/> <br><br><br><br> <button id="s">set to visible class</button> <button id="h"> ...

What is the way to bypass certificate validation when making a Fetch API request in the browser?

The code snippet below is currently being executed in the browser: const response = await fetch(`${url}`, { method: 'POST', headers: { Authorization: `Basic ${authorization}`, }, body: loginData, }) Upon calling this co ...

JQuery table sorter is unable to effectively sort tables with date range strings

I am facing an issue with sorting a column in my table that contains text with varying dates. The text format is as follows: Requested Statement 7/1/2014 - 9/16/2014 When using tablesorter, the sorting does not work properly for this column. You can see ...

What is the process for generating an array of arrays in a React component?

I'm currently working on developing a word-guessing game similar to Wordle using React. The interesting twist in this game is that players have the ability to choose both the number of attempts allowed and the length of the word they are trying to gue ...

Problem with Snowpack's internal module import paths

While working on a project, I am using npx snowpack build --watch instead of the dev command because of a Flask backend. However, I am facing issues with internal imports, specifically modules importing dependencies like Bootstrap importing Popper. The pr ...

Is there a way to remotely access and read text files stored on a server using either JavaScript or Ajax from an IIS6.0 Virtual directory?

Is it possible to use JavaScript or Ajax to read the text from a file on a remote machine (from IIS6.0 Virtual directory) and then copy it into a specific folder on the client machine? ...

Solving an asynchronous variable that is already present in the route provider

In my application, I am facing a problem with resolving dates before calling the ObjectService.get() function. I have two asynchronous functions which need to resolve one of them already in the resolve section of the routeProvider. The issue arises when a ...

Is it possible for numerous directives to utilize an isolated scope on a single element?

Is it possible for two directives on the same element to share an isolated scope that is separate from their parent? Can they both access properties bound to this isolated scope? For instance, if there are two directives on an element <e-directive a-d ...

Preserving Leading Zeros in Java When Parsing and Formatting a Text File

Having trouble deciphering the method to read a file line by line and then format it is proving to be quite the challenge. The main issue at hand is when dealing with a text file assigning a "number" to a corresponding "person". Initially, the number "001" ...

The title for beforeShowDay in bootstrap-datepicker is not functioning as expected

When it comes to inserting text below each day in a datepicker, I attempted to use the beforeShowDay function. According to the documentation, the return value of beforeShowDay should include the following properties: - enabled (Boolean) - classes (Strin ...

Unidentified event listener

I am currently facing an issue where I keep getting the error message "addEventListerner of null" even though I have added a window.onload function. The page loads fine initially but then the error reoccurs, indicating that the eventListener is null. Str ...

I need help figuring out how to represent a nested array within an array of objects within my data instance in Vue

Currently, I have a loop that is showcasing a list of items along with their respective sub-items. The data response payload for this operation appears like the following. I have successfully executed the loop and managed to display it on my frontend desi ...