Using AngularJS to update text content retrieved from a file and display it in a textarea

Is there a way to create a textarea using AngularJS that can be populated either by typing, entering a URL, or uploading a plain text file? While I am able to load the file content into the variable linked to the textarea, I'm facing an issue where getting content from a URL changes the textarea but uploading a file does not. Here is my HTML setup:

<div id="prot2dna" ng-app="serverExe" ng-controller="p2dCTRL as p2d">
    <form novalidate>
        <!-- TEXTAREA -->
        <textarea class="form-control" ng-model="p2d.query.fasta"></textarea>
        <!-- URL SEARCH -->
        <div class="input-group">
        <input type="text" class="form-control" ng-model="p2d.query.uniac">
            <span class="input-group-btn">
                <button class="btn btn-default" type="button" ng-click="p2d.searchUNIP(p2d.query)">
                    Search
                </button>
            </span>
        </div>
        <!-- READ FILE -->
        <span class="btn btn-default my-btn btn-block btn-file">
            UPLOAD FILE
            <input type="file" on-read-file="p2d.query.fasta">
            <!-- This is the same variable linked to the textarea -->
        </span>
    </form>
<div class="checkoutside">
<!-- Variable content gets updated here, whether or not it's displayed in the textarea -->
content:<br>{{p2d.query.fasta}}
</div>
</div>

Here is the JavaScript code snippet:

var exeApp = angular.module('serverExe', [])
/* This directive loads content from a file 
   and updates the variable this.query.fasta.
   However, the textarea itself doesn't get updated */
.directive('onReadFile', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            console.log(attrs)
            var model = $parse(attrs.onReadFile); 
            console.log(model)
            var modelSetter = model.assign;      

            element.bind('change', function(e) {
                scope.$apply(function(){
                    var reader = new FileReader();
                    reader.onload = function(){

                        modelSetter(scope, reader.result);
                    }
                    reader.readAsText(element[0].files[0])
                });
            });
        }
    };
})
.controller('p2dCTRL', function($http, $scope){
    // QUERY
    this.query = { 'fasta' : '', 'uniac' : '', 'fastafile': false, 'unierr': true };

    // Getting content from URL
    this.searchUNIP = function(query) {
        url =  'http://www.uniprot.org/uniprot/'+this.query.uniac+'.fasta';
        $http.get(url)
            .success(function(data){
                query.fasta = data; 
            }).error(function(data){
                query.unierr = true;
            });
    };
});

I need assistance because I am stumped on how to resolve this issue.

Thank you!

Answer №1

One way to achieve this is by utilizing the $parse function in the following manner:

let onDocumentRead = $parse(attrs.onReadDocument);
let reader = new FileReader();

reader.onload = function() {

    let documentContent = reader.result;

    // call parsed function on scope
    scope.$apply(function() {
        onDocumentRead(scope, {
            'content' : documentContent
        });
    });
};

reader.readAsText(element[0].files[0]);

For a complete demonstration, check out this working example: http://jsfiddle.net/23dkhme9/1

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

Determine the card type based on the card number

My array of card types is structured like this: var cards = new Array(); cards [0] = {name: "VISA", length: "13,16", prefixes: "4", checkdigit: true}; cards [1] = {name: "VISA_DELTA/ELECTRON", length: "16", prefixes: "417500,4917,4913", checkdigit: tr ...

An error popped up: "argument list is missing) after"

Encountered an issue: Error message: missing ) after the argument list $('.next-btn').append("<a class="actionsubmit" ng-click="onSubmit('hello.html')">Check</a>"); ...

Is a specific format necessary for express next(err) to function properly?

Recently, while working on my express sub app that utilizes the http-errors module, I encountered an interesting issue. When passing new Forbidden() to the next() callback, it seemed to vanish without triggering any callbacks. However, passing new Error() ...

What is the best way to assign the "active" class to a navigation list item using JavaScript within Bootstrap 4?

Update: just to clarify, I'm working on activating the navbar button based on the current page. I have a navigation bar set up and I am trying to dynamically add an "active" class to the li element when you are on that specific page. However, for som ...

Directive in Angular lacking a defined scope

Can you explain the significance of a directive definition lacking scope:? Additionally, what would be the equivalent if scope: were to be included? For instance, consider this example: .directive('myCustomer', function() { return { templ ...

Animate the React Bootstrap modal only when it is shown or hidden

I am experimenting with the idea of transitioning smoothly from one modal to another in bootstrap Modals for react (using react-bootstrap). However, I am facing challenges due to the fade CSS class causing flickers and unwanted animations. My goal is to h ...

How does webpack identify the index.html file as the entry point for loading the bundle.js file?

I've noticed that without specifying a command to load index.html, webpack is automatically loading the page whenever I make changes in a file. Below are the attached files: webpack.config.js and package.json webpack.config.js var config = { entry: ...

The factory is not receiving any data from the controller

In a hypothetical scenario, picture a facility where inmates are housed in individual cells. My goal is to access a particular cell by invoking the API '/getparameters' which will provide me with the cell number. Subsequently, I intend to utilize ...

What is the most efficient method in React for displaying an array as a table and wrapping every set of five elements with a <tr> tag?

Currently, I am working on rendering a table in React from an array of objects. My approach involves mapping the array to create table elements as shown below: var objects = response.data; var arrayOfTableElements = [] ...

What is causing the reluctance of my Angular test to accept my custom form validation function?

I'm currently facing an issue with testing an angular component called "FooComponent" using Karma/Jasmine. Snippet of code from foo.component.spec.ts file: describe('FooComponent', () => { let component: FooComponent let fixture ...

Modify the date format inside the content of an HTML element or its descendants (excluding their attributes)

I have been trying to reformat some dates using JavaScript. My initial approach was: var regex = /(\d{4})-(\d{2})-(\d{2})/g; $('.container td').each(function() { $(this).html($(this).html().replace(regex, '$3-$2-$1')); ...

Using AJAX to query a database and updating a div tag with the submitted form entries

I need assistance in setting up a webpage with an AJAX form. The idea is that upon submission, the form's values will be used to search and query a database for results, which will then be displayed in the same DIV as the form. Any guidance or help o ...

Converting URL-esque information to JSON using JavaScript

Does anyone have a solution for converting an array of URL-like data into JSON format? For example, how can we convert the array ["a.b.c.d", "a.c.e.f", "a.b.c.g"] into the following JSON structure: items:{ text: "a", items:[ { ...

How can we verify in enzyme that the history.push method was called while utilizing withRouter and connect?

In a stateless React component, I am utilizing withRouter and connect. Within this component, there is a button that triggers a method in props provided by mapDispatchToProps. My goal is to create a test that verifies the button's action of calling h ...

A bug in the modal dialog is causing it to disregard the value of

I want to transfer certain modal properties in this manner service.confirm = function(message, confirmProperties) { return $uibModal.open({ templateUrl: 'app/modal/alert/alert.tpl.html', controller: 'alertCon ...

How to properly handle file uploads and get the correct image path from Node Js (Express) to React Js?

Currently, I am working on my local system developing a file upload feature using node js. My project file structure looks like this: Project ..client .... source code of React App ..Server ....uploads ......avatar ........image.png ....index.js In this ...

Executing a JavaScript function with jQuery

function launch() { $("p").text("Hey there", greet()); } function greet() { alert("Greetings! You have triggered another function"); } HTML: <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button onclic ...

Having trouble with updating AngularJS?

I am facing an issue while updating the guitar object in my AngularJS application. The operation is performed using the updateGuitar controller with ngMock backend. After updating the guitar object, the put request is processed by the carService. However, ...

Exploring the animation potential of HTML5 canvas and Javascript through utilizing putImageData with animated gifs

I am interested in modifying the image data of each frame in an animated gif while it is playing in a web browser, using HTML5 canvas and Javascript. For instance, I would like to convert every frame to grayscale dynamically as the gif plays. Is this achie ...

Associating information with a dropdown menu

My goal is to bind a drop-down using a global variable (the array name). The binding works correctly here: Click here - dropdown is populating fine var name = ['us', 'china', 'kenya', 'us', 'china', &ap ...