[英]Obtain User Input Inside An NgRepeat Directive In AngularJS
我有一个具有ngRepeat指令的AngularJS应用。 在指令内部,我有一个文本框,用户可用来输入数值。 当文本框更改时,我想接受用户输入并对其进行操作。 如何将用户输入传递给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...
};
}]);
})();
$scope
即: $scope.data = [1, 2, 3];
。 ng-change
与ng-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>
如您所见,现在input
每次更改都会调用onChange
函数。
您需要将该值绑定到VM中的某物。 这是一个例子:
(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>
首先,您的输入语法缺少“>”。
其次,您需要在输入中使用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);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.