Plunker:
http://plnkr.co/edit/sm3r4waKZkhd6Wvh0JdB?p=preview
我有一组表单元素,可以由用户动态添加和删除。我想知道如何将每组对象的索引包含为每个对象的“id”属性。
因此对于我有的每组输入:
[{“Selection”:“”,“Text”:“”},{“Selection”:“”,“Text”:“”}]
我如何制作它就像......
[{“Selection”:“”,“Text”:“”,“Id”:“1”},{“Selection”:“”,“Text”:“”,Id:“2”}]
控制器:
function DuplicateInputCtrl($scope) {
$scope.foodTypes = [
{
"code" : "AP",
"type" : "Apple"
},
{
"code" : "CH",
"type" : "Chicken"
},
{
"code" : "GR",
"type" : "Grape"
}
]
$scope.foods = [
{
"Selection": "",
"Text": ""
}
]
$scope.cloneItem = function () {
var itemToClone = { "Selection": "", "Text": "" };
$scope.foods.push(itemToClone);
}
$scope.removeItem = function (item) {
$scope.foods.splice(item, 1);
}
$scope.saveForm = function () {
console.log($scope.foods);
}
HTML:
<body ng-controller="DuplicateInputCtrl" class="container">
<div data-ng-repeat="food in foods">
<div class="form-group title-field">
<label for="">Food {{ $index + 1 }}</label>
<select class="form-control input-full" data-ng-model="food.Selection"
data-ng-options="foodType.code as foodType.type for foodType in foodTypes">
<option value="">Select</option>
</select>
<input type="hidden">
<button data-ng-click="removeItem($index)" class="btn delete-field-{{$index}}">
Delete
</button>
</div>
<div class="form-group">
<textarea class="form-control" data-ng-model="food.Text"></textarea>
</div>
</div>
<button data-ng-click="cloneItem()" class="btn inline">
Add
</button>
<div>
<button class="btn btn-medium" ng-click="saveForm()">Save</button>
</div>
{{ foods | json }}
</body>
答案 0 :(得分:1)
使用$watchCollection
http://plnkr.co/edit/6YWHM9B2a3nP74vr5am4?p=preview
$scope.$watchCollection('foods', function() {
angular.forEach($scope.foods, function(x, i) {
x.id = i;
});
});