简体   繁体   English

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

[英]Storing $index value of dynamically added inputs

Plunker here: 在这里柱塞:

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

I have a set of form elements which can be added and removed dynamically by the user. 我有一组表单元素,用户可以动态添加和删除它们。 I would like to know how I could also include the index of each set of objects as an 'id' property for each object. 我想知道如何将每个对象集的索引作为每个对象的'id'属性包含在内。

So for each set of inputs I have: 因此,对于每组输入,我都有:

[ { "Selection": "", "Text": "" }, { "Selection": "", "Text": "" } ] [{“选择”:“”,“文本”:“”},{“选择”:“”,“文本”:“”}]

How do I make it so that it's like.. 我该如何做才能像

[ { "Selection": "", "Text": "", "Id" : "1" }, { "Selection": "", "Text": "", Id : "2" } ] [{“ Selection”:“”,“ Text”:“”,“ Id”:“ 1”},{“ Selection”:“”,“ Text”:“”,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: 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>

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM