Halcyon
Halcyon

Reputation: 14941

Obtain User Input Inside An NgRepeat Directive In AngularJS

I have an AngularJS app which has an ngRepeat directive. Inside the directive, I have a textbox that a user can use to enter numeric values. When the textbox changes, I want to take the user input and act on it. How do I pass the user input into my 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 get the user input here? -->
  </tr>
</table>


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

    vm.onChange = function (inputValue) {
      // act on the change event...
    };

  }]);
})();

Upvotes: 0

Views: 36

Answers (3)

Ele
Ele

Reputation: 33726

Observations

  • You need to add the model to the $scope i.e: $scope.data = [1, 2, 3];.
  • Directive ng-change works alongside with ng-model, so your need to set that directive to each input, i.e: <input ng-model='d' ng-change='onChange(d)' type="number" value="{{ d }}">

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>

As you can see, now the onChange function is being called for every change in input.

Upvotes: 1

DJDaveMark
DJDaveMark

Reputation: 2855

You need to bind the value to something in the VM. Here's an 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>

Upvotes: 0

Will
Will

Reputation: 410

First thing first, your input syntax is missing a ">".
Second you need to have ng-model on your input.

This is the code:

<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);
    };

Upvotes: 0

Related Questions