vignesh selvarathinam vignesh selvarathinam - 29 days ago 10
AngularJS Question

AngularJs ng-repeat : how to bind the values from <input> which was inside the ng-repeat?



var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope){
//Adding New Check# and Check amount Text Boxes
$scope.texs = [{id: 'tex', value: 'tex1'}];

$scope.add = function() {
var newItemNo = $scope.texs.length+1;
$scope.texs.push({'id':'tex'+newItemNo});
};

//Removing Last Check# and Check amount Text Boxes
$scope.remove = function() {
var lastItem = $scope.texs.length-1;
$scope.texs.splice(lastItem);
};
});

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<div class="col-md-12">
<div class="col-md-6">
<div ng-repeat="tex in texs">
<div class="form-group">
<label>tex:</label>
<div class="col-md-5">
<input type="number" class="form-control" id="tex.id" ng-model="tex.id" maxlength="6"></input>
</div>
<button ng-show="$last"
ng-click="remove()">-</button>
</div>

</div>
<button type="button"
ng-click="add()">Add More</button>
</div>
</div>
<div class="col-md-6">
<label>{{tex.id}}</label>
</div>

</body>
</html>





Above i mentioned my code. here If i did not use the
ng-repeat="tex in texs"
,the label
tex
and
texNo
is displaying the
value
once i entered the values in input. But If I did use the
ng-repeat="tex in texs"
, the
value
is not displayed. I know the code is wrong,but what i want is If i click Add More and entered the values of the second
tex
and
texNo
, I want to display the both of values of
tex
and
texNo
in the Label.

please suggest me with something.

Answer

The tex.id contains a string tex whereas ng-model is expecting a number.

You can use dynamic keys and provide an initial value to it

Inside controller

 $scope.texs = [{'id1': 1}];

 $scope.add = function() {
   var newItemNo = $scope.texs.length+1;
   $scope.texs.push({['id'+newItemNo]:1});
 };

Inside HTML

<div ng-repeat="tex in texs">
              <div class="form-group">
               <label>tex:</label>
               <div class="col-md-5">
                <input type="number" class="form-control" id="{{'id'+($index+1)}}" ng-model="tex['id'+($index+1)]" maxlength="6" />
               </div>
               <button ng-show="$last"
                ng-click="remove()">-</button>
              </div>

             </div>
             <button type="button"
              ng-click="add()">Add More</button>
            </div>

FIDDLE