简体   繁体   中英

How to add and remove text field on click of a button in angular js

I have generated button using ng-repeat directive in angular js. Now I want to generate a textfield inside a div tag on click of that button.

Example buttons -

在此输入图像描述

Example textfields added on click of it -

在此输入图像描述

I am doing this using innerHTML attribute of div tag, like 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 any other better way using angularJS or javascript to do the same so that if I need to remove one or all of the textfields later on, it can be done easily. By removing means deleting and NOT hiding.

(becuase if I want to remove for example textfield 'two' now, I have no idea how I remove it)

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

You can do this by having another ng-repeat which loops over an array you declare within your controller. For example:

In your view:

<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, within your button ng-click logic:

// 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);
}

Try hiding the inputs to start with, then show them if the appropriate 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM