I am having difficulty automatically detecting value changes in AngularJS through programming

Recently, I've started working with angularjs and I'm facing a challenge,
Here's the html code:

<section class="content" ng-app="offer">
    <div ng-controller="OfferController">
    ...
    <input name="Attachment" type="file" class="file_up" onchange="angular.element(this).scope().change(this)" ng-model="Attachment" />
    <span>{{Attachment}}</span> //unable to retrieve it
    ...
    </div>
</section>

and here's the script:

var myApp = angular.module('offer', []);

myApp.controller('OfferController', ['$scope', function ($scope) {
    $scope.change = function (element) {
        if (element.files.length > 0) {
            $scope.Attachment = element.files[0].name;
        }
        else {
            $scope.Attachment = "";
        }
        console.log($scope.Attachment); //can see changed value in console
    }
}]);

image:

While I can see the changed value in the console, I'm struggling to display it on the html side when the input's value changes. Any help would be greatly appreciated. Thank you.

Answer №1

When modifying the model outside of Angular's digest cycle, it is important to manually notify the framework that watchers need to be run again. This can be done using $scope.$apply():

$scope.change = function (element) {
    if (element.files.length > 0) {
        $scope.Attachment = element.files[0].name;
    }
    else {
        $scope.Attachment = "";
    }
    $scope.$apply();
}

A more concise way to achieve this is:

$scope.change = function(element) {
    $scope.$apply(function() {
        $scope.Attachment = element.files.length ? element.files[0].name : '';
    });
}

Demo: http://plnkr.co/edit/6quQlHJIvdD3QwtOhHrB?p=preview

Answer №2

UPDATE: @dfsq made a great point in the comments, highlighting that the ng-change attribute doesn't naturally work with file inputs. I have adjusted the code below to offer an alternate solution.

You can create a custom directive to manage the behavior of a file input yourself, ensuring it updates the property binding in ng-model, though this will be one-way only.

.directive('input', function () {
  return {
    restrict: 'E',
    require: '?ngModel',
    link: function(scope, element, attr, ctrl) {
      if (!ctrl || attr.type !== 'file') {
        return;
      }

      var listener = function() {
        var file = element[0].files[0];
        var value = file && file.name;

        if (ctrl.$viewValue !== value) {
          scope.$apply(function() {
            ctrl.$setViewValue(value); // update ng-model
          });
        }
      };

      element.on('change', listener);
    }
  }
})

This approach eliminates the need for onchange or ng-change; when a user selects a file, the filename is immediately assigned to the property in ng-model.

<input type="file" name="Attachment" ng-model="Attachment" ng-change="change()" />
<span>{{ Attachment }}</span>

Check out the working example on Plunker: http://plnkr.co/edit/K3ZLoqNUPbo991b9ooq3?p=preview

Previous answer: (not suitable for input type="file")

In place of using onchange, opt for ng-change instead.

Replace this:

onchange="angular.element(this).scope().change(this)"

With this:

ng-change="change($event.target)"

I hope this information proves useful.

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

Completes a form on a separate website which then populates information onto a different website

Creating a website that allows users to login and view various complaint forms from government websites or other sources. When a user clicks on a link to file a complaint, they will be redirected to the respective page. However, I am looking for a way to ...

Save a value outside of a code snippet

In my Play Framework project, I am working with a views .html file where I have the following code snippet: <script type="text/javascript"> setInterval(function() { $.get("file2", function(${list1}, ${list2}, ${list3}){ $("#result").h ...

Steps for implementing a delete button in a custom table on yii

I've encountered an issue with a form that uses ajaxSubmitButton to add product items to an HTML table. The ajaxSubmitButton successfully adds items using AJAX to update the table's <tr> and <td> elements. I've also included a de ...

Utilizing additional PHP files to handle the AJAX post request and subsequently execute the PHP script

I have been tasked with a complex assignment that I am struggling to comprehend. Let me provide a brief overview of what is required of me. There are three files involved in this task: 1. An HTML file that sends an AJAX post request to passwrapper.php. 2. ...

Exploring the depths of JSON: Unraveling the secrets of reading dynamic object data

Currently, I am receiving a JSON file from another app and my goal is to parse it in order to extract the data contained within. The JSON includes user-defined dynamic data with changing key/value pairs, which has left me feeling uncertain about how to eff ...

Utilizing React Native to dynamically generate buttons through a loop

I am currently working on retrieving data from the Eventbrite API. The information I am hoping to extract is the event names, which will then be added to a list. Within the render function, I aim to dynamically create buttons based on the number of event ...

Are you looking for a demonstration of "Creative Loading Effects" that triggers when the page is loaded?

I came across this demo for a preloader on my website called Creative Loading Effects, specifically the "3D Bar Bottom" effect, which I find very exciting. However, I noticed that it only loads when we press the button, and not automatically when the page ...

What is the reason behind ASP MVC model binder's preference for JSON in POST requests?

Is there a way to bind data to a model when sending a 'GET' request with JSON.stringify() using AJAX? Currently, the model value is always null when using 'GET', but it works fine with 'POST'. Are there any solutions for this ...

Testing the units of a system ensures that the flow and data storage are reliable

Currently, I'm facing an interesting challenge when it comes to unit testing and the flux data stores. Because the data stores are singletons that are only instantiated once (upon module import), any changes made during unit tests remain persistent. ...

What is the proper method to access state following a change in location?

I'm currently dealing with an issue where I need to transition to the state of another controller. I understand that in this scenario I must modify the location to load the desired controller, but how do I specify which state to enter? It's wort ...

Tips for accessing values in an array in asp.net (or asp-classic for optimal performance)

How can I retrieve data in a JavaScript array using ASP, and then format it in the same way as shown in this PHP example? <script>var chartdata=[{"values":[<?php $conn =mysql_connect("host","root","pass") or die ("we couldn't connect!");mysq ...

Utilizing AngularJS to Showcase Information

I have data retrieved from a database that I want to display in a table. Utilizing Jersey as my back-end framework, I successfully tested the functionality using Postman. However, I am encountering an issue when trying to display this data in the front-end ...

Verify if a value in a MongoDB field exists within an array field of the document

I need to verify if the date stored in the sessionDate field of my MongoDB document exists within the unavailableDates array. Here is the schema I am using: const adminSchema = new mongoose.Schema({ sessionDate:{ type: Date }, unavaila ...

"Exploring the Basics: Diving into Node.js, angular.js, and MongoDB - Uncovering Relationship Modeling and Essential Tips

Transitioning from the Java and relational database world, I am diving into a new project involving an appointment scheduling system using node.js and MongoDB on the backend with Angular.js on the client side. I'm seeking clarification on a few key c ...

Making a POST request with ajax in Django

I encountered some difficulties while attempting to send a POST request using ajax in Django. I have searched various resources, but have not yet found a solution. Below is the javascript code that I am using, following this guide: $.ajax({ url: &apo ...

What causes the conflict between Nodejs usb module and Electron?

Apologies for the lengthy post, but I've been tirelessly searching for a solution online without any luck. My goal is to create a basic Electron application that can display an HTML page (which is working fine) and control a printer through the USB mo ...

Pulling a div from beneath numerous other divs

I have been attempting to create a test case for a web application we are developing and I am on the verge of finding a solution, but there is one final hurdle that has me puzzled... Our requirement is to enable div elements to be draggable (which is work ...

Ajax returns with a successful response, yet the specified action is never executed

Currently assisting with a plugin build on Wordpress and facing an issue with a basic ajax call. I am attempting to pass an object through the method 'grab_object_from_ajax_call,' but the method is not executing as expected. Below is the JavaScri ...

"Utilizing JSON information to create visually appealing graphs and charts

Struggling with syntax and in need of assistance. I have a basic data set that I want to display as a timeline with two filled lines (Time Series with Rangeslider). This is the format of my data set: [{"pm10": 12.1, "pm25": 7.0, "time": "13.08.2018 12:25 ...

Adding a Row to an HTML Table Inside a Form through JavaScript

I'm currently attempting to insert a row into a table that resides within a form using JavaScript. The strange thing is, the code functions perfectly when it's placed outside of the form tags. However, as soon as I enclose the code within the for ...