How to add and remove textbox on button click in angular js

I created a button using the ng-repeat directive in angular js. Now I want to create a textbox inside a div tag when this button is clicked.

Examples of buttons -

enter image description here

An example of text fields added on click -

enter image description here

I am doing this using the innerHTML attribute of the div tag as shown below -

var txt = document.getElementById("paidby").innerHTML;
document.getElementById("paidby").innerHTML=txt+ "<div class='row' style='padding:2px'><div class='col-sm-4'><input type='number' placeholder="+str+"></div></div>";

      

But I want to know if there is another better way, using angularJS or javascript, to do the same so that if I need to delete one or all of the textboxes later, it can be done easily. By removing funds, removing and NOT hiding.

(because if I want to delete, for example, the "two" textbox, I don't know how to delete it)

+3


source to share


2 answers


You don't want to manipulate the DOM inside your controller. Often, there are better ways to do this within the framework that Angular provides.

You can do this by adding another ng-repeat that iterates over the array that you declare in your controller. For example:

In your opinion:



<section id="paidby" ng-repeat="textfield in textfields">
  <div class='row' style='padding:2px'>
    <div class='col-sm-4'>
      <input type='number' placeholder="{{textField.str}}" ng-model="textField.value">
    </div>
  </div>
</section>

      

In your controller, inside your ng-click button, the logic is:

// To add:
$scope.textFields.push({ str: someVariable, value: someValue });

// To remove:
var index = $scope.textFields.map(function(t) { return t.value; }).indexOf(someValue);
if (index !== -1) {
  $scope.textFields.splice(index, 1);
}

      

+2


source


Try to hide the input to start, then show them if the corresponding button is clicked:



<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

<div ng-app="" ng-init="array=['one','two','three','four','five']; show=[false,false,false,false,false]">

<button ng-repeat="item in array" ng-click="show[$index] = !show[$index]">{{item}}</button>
<br>
<input type="text" ng-repeat="item in array" placeholder="{{item}}" ng-if="show[$index]" />

</div>
      

Run codeHide result


+1


source







All Articles