[英]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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.