在AngularJS中获取NgRepeat指令内的用户输入

时间:2018-01-26 22:13:00

标签: javascript angularjs angularjs-directive angularjs-ng-repeat

我有一个AngularJS应用程序,它有一个ngRepeat指令。在指令中,我有一个用户可以用来输入数值的文本框。当文本框发生变化时,我想获取用户输入并对其进行操作。如何将用户输入传递到ngChange事件?

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

  }]);
})();

3 个答案:

答案 0 :(得分:1)

观察

  • 您需要将模型添加到$scope,即:$scope.data = [1, 2, 3];
  • 指令ng-changeng-model一起使用,因此您需要将该指令设置为每个输入,即:<input ng-model='d' ng-change='onChange(d)' type="number" value="{{ d }}">

请看这段代码:

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>

如您所见,现在onChange中的每次更改都会调用input函数。

答案 1 :(得分:0)

您需要将值绑定到VM中的某些内容。这是一个例子:

&#13;
&#13;
(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]);
    };
  }]);
})();
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

首先,您的输入语法缺少“&gt;”。
其次你需要输入ng-model。

这是代码:

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