TheTechGuy
TheTechGuy

Reputation: 1608

Adding button functionality individually in angularjs template

I have a template. In the template, there are three boxes. Each box has add button, which will add an input field in that box. I have tried the following codes.

HTML

<div class="row">
        <div ng-repeat="item in items2">
          <div class="theBox">
            <button class="btn btn-success" ng-click="addItem()">add</button>
            <h6>{{item.key}}</h6>

            <input ng-model="item.value">
          </div>
        </div>

</div>

AngularJs

 $scope.items2 = [
      {
        "key" : "a",
        "value" : []
      },
      {
        "key" : "b",
        "value" : []
      },
      {
        "key" : "c",
        "value" : []
      }
  ];


  $scope.addItem = function(){
    console.log("clicked ")
   angular.forEach($scope.items2, function(mm){
     mm.value.push({})
   })

  }

The Problem: If I click on add, it's creating an object inside each value, maybe because I have used the forEach-loop for each value. How can I add it individually?

Also The input tag is not added as well, how can I fix that ?

Upvotes: 2

Views: 414

Answers (2)

illeb
illeb

Reputation: 2947

Your question it's not exactly clear.

If you are going to

add an input field in that box

every time you click on the add button, then you will need another ng-repeat in your HTML. Something like:

<div class="row">
    <div ng-repeat="item in items2">
      <div class="theBox">
        <button class="btn btn-success" ng-click="addItem(item)">add</button>
        <h6>{{item.key}}</h6>

        <input ng-repeat="itemValue in item.value" ng-model="itemValue.text">
      </div>
    </div>

and your javascript to:

$scope.addItem = function(item){ 
    item.value.push({text:""});
}

Upvotes: 2

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

which will add an input field in that box.

If I understand you right you want to add <input>s to specific box.

I would write something that:

<div class="row">
        <div ng-repeat="item in items2">
          <div class="theBox">
            <button class="btn btn-success" ng-click="addItem(item)">add</button>
            <h6>{{item.key}}</h6>
          <div ng-repeat="value in item.values">
             <input  ng-model="value.text">
            </div>    
          </div>
        </div>
</div>

and method will be:

 $scope.addItem = function(selectedItem){
   selectedItem.values.push({text:""});  
 }

Demo Plunker


Tips:

  • If you have list og inputs, the good practice to name it values and not value in { "key" : "a", "value" : [] },
  • input ng-model is based on string and not object so will be better to set {text:""} and <input ng-model="value.text">

Upvotes: 2

Related Questions