如何从 ng-repeat 中删除特定元素?

How to remove specific element from ng-repeat?

我在使用表单中的 ng-repeat 时遇到了一些问题。

我有一个表单,当我单击一个按钮时,会出现一组输入字段和一个删除按钮。我正在为此使用 ng-repeat。当您单击删除按钮时,我希望能够删除该特定输入组。不过,按照我现在编写的方式,无论我点击哪里,单击删除按钮都会从列表底部删除输入。这里有一个 GIF 可以更好地解释它:

我认为这只是 ng-repeat 中特定 $index 的简单拼接,但显然不是(除非我遗漏了什么)。

这是 ng-repeat 的 HTML:

<div class="form-group">
  <label class="col-sm-2 control-label">More Parameters</label>
    <button type="button" ng-click="addParameterFields()">Add Parameter</button>
      <div class="col-sm-10 col-sm-offset-2">
        <div ng-repeat="params in formData.gameIdParams track by $index" class="controls parameters">
          <input type="text" ng-model="formData.gameIdParams.id[$index]"
            name="gameIdParamsId"
            class="col-sm-3"
            autocomplete="off"
            placeholder="Type of Input"
            validation-field-required="true"/>
          <input type="text" ng-model="formData.gameIdParams.label[$index]"
            name="gameIdLabel"
            class="col-sm-3"
            autocomplete="off"
            placeholder="Placeholder Text to add in Input Field"
            validation-field-required="true"/>
          <input type="text" ng-model="formData.gameIdParams.validationRegex[$index]"
            name="gameIdvalidationRegex"
            class="col-sm-3"
            autocomplete="off"
            placeholder="Regex used for Validation (optional)"
            validation-field-required="false"/>
          <button ng-click="formData.gameIdParams.splice($index,1)">Remove</button>
        </div>
     </div>
</div>

这是我用于添加表单的逻辑:

$scope.addParameterFields = function() {
  console.log('CLICKED');
  if($scope.formData.gameIdParams === null || $scope.formData.gameIdParams === undefined) {
    $scope.formData.gameIdParams = [];
  }
  $scope.formData.gameIdParams.push({
    id: "",
    label: "",
    validationRegex: ""
  });
  console.log($scope.formData);
};

在此先感谢您的帮助!

你应该创建一个像这样的函数:

ng-click="removeForm($index)"

$index对应你的ng-repeat循环的迭代次数。

然后,在您的控制器中,只需:

$scope.removeForm = function(index){
   delete yourObj[index];
   // or
   yourObj.splice(index, 1);
}

编辑

替换:

formData.gameIdParams.your_variable[$index]

作者:

formData.gameIdParams[$index].your_variable

或:

params.your_variable