AngularJS - Use ng-repeat to print inputs based off of a number
刚接触AngularJS,对如何使用ng repeat有疑问。
目前,我只能找到您从服务中读取的示例,然后在这些示例上进行ng重复循环。
我的情况是,管理员可以为客人创建邀请并设置一个名为:
1 | total_in_party = 4; |
现在,基于"聚会中的总人数",我想为聚会中的每个客人输入3个字段。
像:
1 2 3 | <input type="text" ng-model="guest.first_name" /> <input type="text" ng-model="guest.last_name" /> <select ng-model="selectedGuestMeal" ng-options="meal.id as meal.name for meal in meals"></select> |
对于这种情况,它应该4次打印这3个输入字段。
我觉得我很接近,只是需要知道如何创建聚会对象,如果我还没有数据存储在其中?
如果我做这件事完全错了-别犹豫,告诉我!
最近我不得不解决这个确切的问题。实际上,您需要在您的作用域中创建一个来宾对象数组,然后使用
在这里看到我的解决方案的工作演示:http://plnkr.co/edit/2ayslye0icrgxr7lm0hr?P=预览
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | app.controller('MainCtrl', function($scope) { $scope.numberOfGuests = 1; $scope.guests = []; addGuests($scope.numberOfGuests); // When the number of guests changes, we want to repopulate the // array of guest info (in a non-destructive manner). $scope.$watch('numberOfGuests', function (newValue, oldValue) { if (!newValue) { return; } newValue = parseInt(newValue, 10); oldValue = parseInt(oldValue, 10); // If the number of guests increased, add some empty objects to the array. if (!isNaN(oldValue) && newValue > oldValue) { var numberOfGuests = newValue - oldValue; addGuests(numberOfGuests); } else { // Otherwise reset length of array $scope.guests.length = newValue; } }); function addGuests(numberToAdd) { if (!isNaN(numberToAdd) && numberToAdd > 0) { for (var i = 0; i < numberToAdd; i++) { $scope.guests.push({}); } } } }); |
这里是风景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <body ng-controller="MainCtrl"> <form> <p> Nunmber of Guests <input type="number" ng-model="numberOfGuests"> </p> <table> <tr ng-repeat="guest in guests track by $index"> <td>{{$index + 1}}</td> <td><input type="text" ng-model="guest.name"></td> <td><input type="text" ng-model="guest.email"></td> </tr> </table> </form> [cc lang="javascript"]{{guests | json}} |
<正文>< /代码>
您可以观看
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $scope.$watch('total_in_party', function(newValue, oldValue) { if (newValue != null) { console.log(newValue, oldValue); if (newValue > oldValue) { //add var i = newValue - oldValue; for (var k = 0; k < i; k++) { $scope.party.push({ first_name:"", last_name:"", selectedGuestMeal: null }); } } else if (newValue < oldValue) { //subtract var i = oldValue - newValue; $scope.party.splice(0, i); } } }); |
比如看这个普朗克
可以在基于
1 2 3 4 5 6 7 8 9 10 | function initGuests(totalInParty) { $scope.guests = []; for (var i = 0; i < totalInParty; i++) { $scope.guests[i] = { first_name: '', last_name: '', meal: '' }; } } |
在你的
1 2 3 | <input type="text" ng-model="guests[$index].first_name" /> <input type="text" ng-model="guests[$index].last_name" /> <select ng-model="guests[$index].meal" ng-options="meal.id as meal.name for meal in meals"></select> |
没有测试过它,但它应该可以工作:)