Search code examples
angularjsangularjs-ng-repeatangular-ngmodel

Modify model on change of input value inside ng-repeat


I have a table where I list some products with some inputs, basically what I want is to change an input value when another changes, here's the <tr>:

<tr ng-repeat="bought_product in vm.bought_products track by bought_product.id">
    <td>
        {{ bought_product.name }}
    </td>
    <td>
        <input type="number" class="form-control"
               min="1" max="1000" placeholder="#"
               ng-model="bought_product.quantity">
    </td>
    <td>
        <div class="input-group">
            <span class="input-group-addon">$</span>
            <!-- This is the input where I'll insert a price -->
            <input type="number" class="form-control no-spin"
                   min="1" max="1000" placeholder="#" ng-change="vm.calculateVatPrice(bought_product.price)"
                   ng-model="bought_product.price">
        </div>
    </td>
    <td>
        <div class="input-group">
            <span class="input-group-addon">$</span>
            <!-- This input will automatically be filled -->
            <input type="number" class="form-control no-spin"
                   min="1" max="1000" placeholder="#"
                   ng-model="bought_product.vat_price">
        </div>
    </td>
</tr>

Solution

  • You will have to replace your

    ng-change="vm.calculateVatPrice(bought_product.price)"
    

    by

    ng-change="vm.calculateVatPrice(bought_product)"
    

    and inside your vm.calculateVatPrice function you will have to calculate and set the vat_price like this

    calculateVatPrice = function (product) {
        product.vat_price = product.price * 1.18;
    }
    

    Of course you have to replace this by your actual business logic for calculating the vat-price.

    So the trick is to hand over the reference to the object of the product and update the value accordingly in place.