3

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 -

enter image description here

Example textfields added on click of it -

enter image description here

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)

Anurag Rana
  • 1,429
  • 2
  • 24
  • 48
  • Create the input element and use its id as a reference when deleting. – Kyle Emmanuel May 24 '15 at 23:47
  • I have a strong suspicion that you are not understanding the use case for Angular. See if this [question/answer](http://stackoverflow.com/a/15012542/968155) makes sense to you before you proceed. – New Dev May 25 '15 at 00:07

2 Answers2

2

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);
}
Mike Lawson
  • 735
  • 6
  • 12
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>
omikes
  • 8,064
  • 8
  • 37
  • 50