Detecting changes in AngularJs elements

Below is the code snippet provided:

  handleFileSelect = (evt) ->
    console.log(1)
    file = evt.currentTarget.files[0]
    reader = new FileReader()
    reader.onload = (evt) ->
      $scope.$apply ($scope) ->
        $scope.myImage = evt.target.result
      reader.readAsDataURL(file)
  angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect)

Here is the corresponding HTML:

<div class="form-group ng-scope">
  <label class="col-sm-2 control-label" for="image">Image:</label>
  <div class="col-sm-10">
    <div class="cropFile">
      <input id="fileInput" type="file">
    </div>
  </div>
</div>

I am expecting to see '1' in the console after changing a file in #fileInput. However, nothing appears when I select a file. How can this issue be resolved? Thank you!

Answer №1

To implement this functionality, you can create a custom directive.

I have developed a directive called upload

HTML Section

<div><input style="margin: 0 auto;" type="file" id="fileInput" upload></div>

Javascript for Directive

myapp.directive('upload', function($rootScope) {
return {
    restrict: 'EA',
    link: function(scope, elem, attrs) {
        elem.on("change" ,function(evt) {
            var file = evt.currentTarget.files[0];
            var reader = new FileReader();
            reader.onload = function(evt) {
                scope.$apply(function($scope) {
                    $rootScope.myImage = evt.target.result;
                    console.log($rootScope.myImage);
                });
            };
            reader.readAsDataURL(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

Extending a Sub-Object in JavaScript

I'm attempting to include new attributes to the sub-object within object1. However, I am facing issues with it being overwritten. const object1 = { a: 1, b: 2, c: 3, sub: { e: 1, f: 2 } }; const object2 = Object.assign({ j: 4, ...

The PHP-generated table is not being appended to the specified div with jQuery

I am currently working on developing a webpage that displays live forex rates to users. I am pulling the values from a feed and echoing them into a table. My goal now is to use jQuery to show this table to the user. The issue I am facing is that when I tr ...

Dots are used to indicate overflow of title in React Material UI CardHeader

Is there a way to add ellipsis dots to the title in my Cardheader when it exceeds the parent's width (Card width)? Here is what I have attempted so far: card: { width: 275, display: "flex" }, overflowWithDots: { textOverflow: &apo ...

Tips for keeping components mounted despite changes in the path

How can I maintain state in React routes to prevent unmounting when switching between them? In my application, it's crucial to keep the state intact during route changes. When changing routes, the respective components mount and unmount. How can this ...

Utilizing *ngfor in Angular 7 to Group and Display Data

I currently have incoming data structured like this in my Angular application Visit this link to see the data format https://i.stack.imgur.com/jgEIw.png What is the best way to group and sort the data by State and County, and present it in a table as sh ...

Struggles with ajax and JavaScript arise when attempting to tally up grades

Currently, I am facing an issue with my JavaScript. The problem arises when trying to calculate marks for each correctly chosen answer based on information from the database. If an incorrect answer is selected, the marks are set to '0', otherwise ...

Decode my location and input the address before validating it

While I have come across numerous plugins that enable geolocation and display it on a map, I am searching for something unique. I am interested in implementing geocoding when a user visits the page with an option to "allow geolocation." If the user agrees ...

I am unable to comprehend the function definition

I have familiarity with different types of JavaScript function declarations such as expression functions and anonymous functions. However, I am unsure about the syntax used in these two specific functions: "manipulateData: function (input)" and "getDataByI ...

Does the PHP include function act as an HTTP request?

After coming across an article highlighting the negative impact of using excessive HTTP requests on server speed, I started wondering about the performance implications of PHP includes. Specifically, I'm curious if sending 4 AJAX requests compared to ...

Automatically assigning a default dynamic value to a dropdown option using Vue.js

I need to set a default selected value for the select option element, but I am facing difficulty in achieving the desired result. <template> <select v-model="tutor_work.start_year"> <option>{{tutor_work.start_year}}< ...

Show the time in hours and minutes (00:00) while rounding off seconds to the nearest minute

I need the time to always display with leading zeros when less than 10. For example, if a task took 3 hours, 7 minutes, and 33 seconds, it should be shown as 03:08. Currently, I have the buttons disabled after they are clicked to prevent restarting the ti ...

Exploring the wonders of Jasmine coding with jQuery

I am relatively new to conducting Jasmine tests. I have a basic understanding of how to install it and use simple commands like toEqual, toBe, etc. However, I am unsure of how to write test code for this particular jQuery function using Jasmine. if ($(&ap ...

A helpful guide on passing a component as a prop to a child class and incorporating it within the child component along with additional props

Within my parent class, I have loaded a child class component and passed another component to it as a prop. In the childclass component, I am trying to display that component. <EditRecordModal show={this.state.showEditModal} onHide={this.handle ...

unable to utilize the library three.js

I stumbled upon an interesting animation on Codepen that uses blocks to reconstruct a map image. The necessary JavaScript files are three.min.js and TweenMax.min.js. I copied the links from Codepen and pasted them into my HTML using <script src="">&l ...

Cypress and VueJS: How to target elements that are dynamically generated following a specific user interaction

I am currently testing a new feature where a button will only appear for the user to click after they have completed another action. Before proceeding with the action, I am verifying if the button exists: cy.get('span') .contains('Selec ...

Can global scope be injected into a class instantiated in ES6, also known as a singleton?

Before I get started, I want to apologize in advance for the lengthy code that is about to follow. It may make this question seem a bit bloated, but I believe it's necessary for understanding my issue. Imagine we have a predefined MainModule: ' ...

When an Ajax call is made, my .html page transforms into a .php page using jQuery

The Issue While using my PHP function to send emails, everything goes smoothly. However, I'm facing an issue where I don't want the page to refresh, so I've implemented AJAX in the code below: reservation.html <form class="form-horizon ...

Discovering indistinguishable "Feeling Fortunate" inquiries

My goal is to create a program on my website that can compare the top search results for different queries. For instance, I want it to recognize that the top search result for "twelve" and "12" is the same, leading to https://en.wikipedia.org/wiki/12_(numb ...

"Socket io Simplified: Embracing the Power of Drag

I'm currently in the process of developing a multiplayer card game using node, express, and socket io. However, I am facing some difficulties when it comes to transmitting drag and drop actions performed by one player to another connected player' ...

The function inputLocalFont.addEventListener does not exist and cannot be executed

Help needed! I created a code to add images using PHP and JS, but I'm encountering an error in my JS that says: inputLocalFont.addEventListener is not a function Here's the code snippet: <div> <img src="<?php echo $img_path.& ...