gpt4 book ai didi

javascript - 存储动态添加的输入的 $index 值

转载 作者:行者123 更新时间:2023-11-28 00:56:49 25 4
gpt4 key购买 nike

这里是笨蛋:

http://plnkr.co/edit/sm3r4waKZkhd6Wvh0JdB?p=preview

我有一组表单元素,可以由用户动态添加和删除。我想知道如何将每组对象的索引作为每个对象的“id”属性包含在内。

因此,对于我的每组输入:

[ { "选择": "", "文本": ""}, { "选择": "", "文本": ""} ]

我怎样才能让它看起来像..

[ { "选择": "", "文本": "", "Id": "1"}, { "选择": "", "文本": "", Id : "2"} ]

Controller :

 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>

最佳答案

使用$watchCollection http://plnkr.co/edit/6YWHM9B2a3nP74vr5am4?p=preview

  $scope.$watchCollection('foods', function() {
angular.forEach($scope.foods, function(x, i) {
x.id = i;
});
});

关于javascript - 存储动态添加的输入的 $index 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26128083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com