AngularJS新手,对如何使用ng-repeat有疑问。
目前,我只能找到您从服务中读取的示例,然后对其进行ng-repeat循环。
我的情况是管理员可以为访客创建邀请并设置名为:
的属性total_in_party = 4;
现在基于" total_in_party"我希望为聚会中的每位客人提供3个输入字段
像:
<div ng-repeat="guest in party">
<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>
</div>
对于这种情况,它应该打印这3个输入字段4次。
我认为我很接近,如果我没有存储数据,只需知道如何创建派对对象吗?
如果我这样做完全错了 - 请不要犹豫通知我!
答案 0 :(得分:3)
我最近必须解决这个问题。您基本上需要在作用域中创建一个来宾对象数组,然后使用ng-repeat
将数组绑定到表单。
在此处查看我的解决方案的工作演示:http://plnkr.co/edit/2aYSLYe0IcRGXR7Lm0HR?p=preview
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({});
}
}
}
});
这是视图
<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>
<pre>{{guests | json}}</pre>
</body>
答案 1 :(得分:1)
您可以根据guests
在控制器中实例化$ scope上的total_in_party
属性;
function initGuests(totalInParty) {
$scope.guests = [];
for (var i = 0; i < totalInParty; i++) {
$scope.guests[i] = {
first_name: '',
last_name: '',
meal: ''
};
}
}
在ng-repeat
中使用$index
,如下所示:
<div ng-repeat="guest in guests">
<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>
</div>
没有测试过,但它应该有效:)
答案 2 :(得分:1)
您可以观看total_in_party
号码并根据其添加/减少来宾
<强> JS 强>
$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);
}
}
});