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)

2
  • Create the input element and use its id as a reference when deleting. Commented May 24, 2015 at 23:47
  • I have a strong suspicion that you are not understanding the use case for Angular. See if this question/answer makes sense to you before you proceed. Commented May 25, 2015 at 0:07

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.