Collecting User Input Within an NgRepeat Directive Using AngularJS

I am working on an AngularJS application with an ngRepeat directive. Within this directive, there is a textbox that allows users to input numeric values. I want to capture this user input and perform actions based on it whenever the textbox changes. How can I successfully pass the user input into the ngChange event?

<table>
  <tr ng-repeat="d in vm.data">
    <td><input type="number" value="{{ d }}" ng-change="vm.onChange(userInput)" /></td> <!-- How can I access the user input within this element? -->
  </tr>
</table>


(function () {
  var app = angular.module('TestApp', []);
  app.controller('TestCtrl', [function () {
    var vm = this;
    vm.data = [1, 2, 3];

    vm.onChange = function (inputValue) {
      // handle the change event here...
    };

  }]);
})();

Answer №1

Insights

  • Make sure to include the model in the $scope like this: $scope.data = [1, 2, 3];.
  • The ng-change directive should be used with the ng-model directive on each input element, for example:
    <input ng-model='d' ng-change='onChange(d)' type="number" value="{{ d }}">

Take a look at this code snippet:

var app = angular.module('TestApp', []);
app.controller('TestCtrl', ['$scope', function($scope) {
  $scope.data = [1, 2, 3];

  $scope.onChange = function(inputValue) {
    console.log(inputValue);
  };
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>

<div ng-app='TestApp'>
  <table ng-controller="TestCtrl">
    <tr ng-repeat="d in data">
      <td>
        <input ng-model='d' ng-change='onChange(d)' type="number" value="{{ d }}">
      </td>
      <!-- How can I get the user input here? -->
    </tr>
  </table>
</div>

By following this structure, the onChange function will be triggered whenever there is a change in the input field.

Answer №2

First and foremost, make sure to add the missing ">" in your input syntax.
Additionally, don't forget to include ng-model on your input element.

Here's the code snippet:

<tr ng-repeat="d in vm.data">
    <td><input type="number" ng-change="vm.onChange(d.val)" ng-model="d.val"></td> 
</tr>

var vm = this;
    vm.data = [{val:1}, {val:2}, {val:3}];

    vm.onChange = function (val) {
      console.log(val);
    };

Answer №3

To properly link the value to a component in the VM, you can follow this example:

(function () {
  var app = angular.module('TestApp', []);
  app.controller('TestCtrl', [function () {
    var vm = this;
    vm.data = [1, 2, 3];
    vm.nums = [];

    vm.onChange = function (i) {
      console.log(nums[i]);
    };
  }]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-cotroller="TestCtrl">
  <tr ng-repeat="d in vm.data">
    <td>
      <input type="number" ng-model="vm.nums[$index]"
             ng-change="vm.onChange($index)">
    </td>
  </tr>
</table>

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

How can state values be transferred between components?

I have come across various answers on different platforms but haven't been able to achieve the desired results. That's why I am reaching out with this question. So, my question is related to 3 files named: App.js, SignUp.js, and Welcome.js. My ...

What is the best way to retrieve an object instead of an array?

When attempting to retrieve a JSON Object, I unexpectedly received an array instead. My query is based on the primary key, so I anticipate only one result. This is my current method : router.get("/student_info/:id", (req, res, next) => { connecti ...

Step-by-step guide for creating a "load more on scroll" feature with Node.js and MongoDB

I currently have a Node server utilizing Express+Typescript to connect to a MongoDB database using Mongoose. Within the database, there is a collection named Products that the frontend (Angular 9) requests in order to display them. At the moment, the serv ...

Converting the information retrieved from Firebase into a different format

My Project: In my Angular SPA, I am trying to retrieve data from Firebase and display specific values on the screen. Approach Taken: The data returned from Firebase looks like this: Returned Data from Firebase Error Encountered: In order to display the ...

Nested loops seem to override previous results with the final output

I am attempting to iterate through an array of months nested within an array of 'years' in order to calculate a count for each month using a custom angular filter. Initially, I set up the structure I will be looping through in the first while loo ...

What could be the reason for my user input not being captured and saved as variable data on the HTML webpage?

Here is the code I am working with: var g = document.getElementById("al").value; function start() { document.getElementById("test2").innerHTML = typeof(g) + parseFloat(g); } <p id="test2">Output will be displayed here:</p> <form> ...

transmitting error messages from a service to a controller in AngularJS

Controller.js var vm = this; vm.admin = {}; vm.add = function () { API.addAdmin(token, vm.admin) .then(function (resp) { vm.hideForm = true; vm.showButton = true; Notify.green(resp); }, function (re ...

Adjust Text to Perfectly Fit Button

I am developing a quiz using bootstrap and javascript. One issue I encountered is that the text in the buttons can sometimes be longer than the button itself. This results in the text not fitting properly within the button, making it unreadable on mobile ...

How can jQuery obtain the value of an ID or class that does not exist?

My current task involves checking if an object has the same id on the DOM because I am working on developing a modal window library. The issue arises when I try to execute the following code in the browser's console: $("#anonexistingid"); It return ...

Spring Security 3 does not support the use of static resources

I am facing difficulty in configuring static resources (such as js, css, images) in spring security 3. Here is my configuration file: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/s ...

Pictures are not showing up in the gallery after they have been saved

if (action.equals("saveToGallery")) { JSONObject obj = args.getJSONObject(0); String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null; String imageName = obj.has(" ...

Managing background tasks with Node.js in real-time

I am currently faced with the challenge of managing background events. When a user is temporarily banned, we save the ban expiration in our database to ensure they are unbanned at the right time. However, my current code checks every ban every 10 seconds ...

Is searching for duplicate entries in an array using a specific key?

Below is an array structure: [ { "Date": "2020-07", "data": [ { "id": "35ebd073-600c-4be4-a750-41c4be5ed24a", "Date": "2020-07-03T00:00:00.000Z", ...

Learn how to make a contenteditable div perform tab spacing with a simple keystroke of the tab key

I've been trying to figure out how to make this contenteditable div add tab spacing when I press the tab key, but so far no luck. If anyone has a solution for this issue, please feel free to share. You can use an ID, class, or any other method to get ...

The AngularJS ng-class expression checks for a substring that matches the current day's date

In the code snippet below, I have a table populated with rows using ng-repeat and a JSON data source. <tbody> <tr ng-repeat="roll in filtering(JSON) | orderBy:[sortType,'Cutoff']:sortReverse | filter:q as results" ng-class="{ ' ...

Reading very large .csv files using the FileReader API in JavaScript with only HTML/jQuery can be accomplished by following these

Having trouble handling a large .csv file over 40 MB (with more than 20,000 lines) and displaying it as an HTML table. I'm developing a system using only pure HTML + JQuery. This is the format of my .csv worksheet: ================================== ...

Turning a JavaScript function into jQuery

Is there a way to convert this JavaScript selected code into jQuery? I need to target a button class instead of an ID, and I've heard that using jQuery is the simplest way to achieve this. var playButton1 = $('.playButton1'); playButton1.o ...

The ng-repeat in the inner loop is excluding the initial element of my array and subsequently placing them in the final HTML tag

I am facing a challenge with converting a JSON array into HTML using angular's ng-repeat. The JSON structure I'm working with looks like: data:{ thing_one:[{ id:1, fields:[{ .... }] }, { id:2, fields:[{ .... ...

Can you explain the distinction between querying a database and making a request to an endpoint?

Recently, I've been diving into learning mongoose but came across a code that left me puzzled. I'm curious as to why we include the async keyword at the beginning of the callback function when querying a database. Isn't it already asynchron ...

Angular directive for Bootstrap Datepicker: Displaying only months and years

I have been utilizing the datepicker feature from Angular directives for bootstrap. My goal is to only display months and years in the datePicker pop-up, but unfortunately, I have not been able to figure out how to achieve this. I attempted a similar meth ...