Arfat
Arfat

Reputation: 127

get values from each ng-repeat input elements

I have the following code where I have added 5 input texts via ng-repeat and now am trying to fetch each of the input element's values. I am hitting some roadblock, so please help me out on how to fetch individual values.

HTML:

<form class="quick-add-form" method="post">
    <label class="quick-add-label">Enter the catalog number and quantity</label>
    <div class="quick-add">
        <div class="catalog-list">
            <label class="catalog-number-label" for="catalog-number-input">Catalog Number:</label>
            <div ng-repeat="values in catalogNumber(number) track by $index">
                <input id="catalog-number-input-{{$index}}" class="catalog-number-input" 
                type="text" ng-model="catalog.description" validate-input>
            </div>
        </div>
        <div class="qnty-list">
            <label class="pdt-qnty-label" for="pdt-qnty-input">Quantity:</label>
            <div ng-repeat="values in catalogNumber(number) track by $index">
                <input id="pdt-qnty-input-{{$index}}" class="pdt-qnty-input" type="number" pattern="[0-9]*" 
                    inputmode="numeric" min="1" max="999" ng-model ="catalog.quantity" name="qty" 
                    maxlength="3">
            </div>
        </div>
    </div>
    <div>
        <button type="submit" class="btn btn-danger cta-button quick-add-btn" 
        ng-click ="quickAdd(catalog)">Add to List</button>
    </div>
</form>

and controller:

$scope.catalog = {};
$scope.catalogNumber = catalogNumber;
$scope.initializeModal = initializeModal;
$scope.quickAdd = quickAdd;

function catalogNumber(num) {
    return new Array(num);  
}

function quickAdd(val) {
    console.log(val);
}

function init() {
    $scope.number = 5;
    $scope.catalog.quantity = 1;
}

I am pretty sure its because of indexing and which is why by adding value in one input, its adding same value in all at once. But I am not sure how/where to use the $index properly to achieve the result.

Thanks.

Upvotes: 0

Views: 37

Answers (1)

rrd
rrd

Reputation: 5977

Perhaps a better way would be to use the model? For example:

<div ng-repeat="values in catalogNumber(number) track by $index">
  <input
    id="catalog-number-input-{{$index}}"
    class="catalog-number-input" 
    type="text"
    ng-model="catalog.description[$index]"
    validate-input>
</div>

Now in your controller:

catalog.description = [];

Then you have an array of objects, which you can perform your math on:

var total = _.sum(Object.values(catalog.description));

Edit: I had forgot I was using Lodash/Underscore there, but if you wanted to use standard JS you could use a standalone method, or reduce etc.,

Upvotes: 1

Related Questions