Prakash kumar Guru Prakash kumar Guru - 1 year ago 60
AngularJS Question

add and remove text field dynmaically in angularjs

I want to add and remove text fields in angularjs with an add button click. And in the right side of the text fields, which were added there should be a remove option. While I click on the remove the text field should delete.

Answer Source

You can use ng-repeat to achieve this functionality. You'll have to add an object in a $scope object's array everytime the user presses Add button and removing the object when the user presses - button.

Here's the code sample.

<span ng-click="addTextBox()"> + </span>
<div ng-repeat="textBox in textBoxes">
    <input type='text' />
    <span ng-click="removeTextBox("> - </span>

The controller goes like this

$scope.textBoxes = [];
$scope.addTextBox = function() {
    $scope.textBoxes.push({id: $scope.textBoxes.length +1});
$scope.removeTextBox = function(id){
    var indexToRemove;
    for(i = 0; i < $scope.textBoxes.length; i++){
        if($scope.textBoxes[i].id === id){
            indexToRemove = i;
        $scope.textBoxes.splice(indexToRemove, 1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download