Reputation: 157
I'm having some trouble with an ng-repeat in a form.
I have form where when I click a button, a group of input fields appear along with a remove button. I am using an ng-repeat for this. I want to be able to remove that specific group of inputs when you click the remove button. The way I have it written right now, though, clicking the remove button removes the inputs from the bottom of the list, no matter where I click. Here's a GIF to better explain it:
I thought it would just be a simple splice at that specific $index within the ng-repeat, but apparently not (unless there's something I'm missing).
Here is the HTML for the ng-repeat:
<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>
And here is the logic I use for adding the forms:
$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);
};
Thanks in advance for any help!
Upvotes: 0
Views: 858
Reputation: 1057
You should create a function like :
ng-click="removeForm($index)"
$index corresponding to the iteration number of your ng-repeat loop.
Then, in your controller, just :
$scope.removeForm = function(index){
delete yourObj[index];
// or
yourObj.splice(index, 1);
}
EDIT
Replace :
formData.gameIdParams.your_variable[$index]
By :
formData.gameIdParams[$index].your_variable
Or :
params.your_variable
Upvotes: 1