Search code examples
javascriptangularjsdynamicsumangular-ngmodel

angularjs create dynamic divs based on click and calculate in rows totals


I have a to dynamically create rows with some values(fixed values) in it and i want to show this values and the SUM of this values for EACH row. Then i want to update some of this values and see that also my SUM change:

here is my code: HTML:

<div id="containerEsterno" class="row m-lg border-bottom">
    <button ng-click="vm.add()">New Item</button>
    <br>
    <div class="row m-xs" id="containerInterno">
        <label>question</label>
        <label>text</label>
        <label>checkbox</label>
        <label>addendo1</label>
        <label>addendo2</label>
        <label>risultato</label>
    </div>
    <div class="row" id="containerInterno" ng-repeat="item in vm.items">
        <input ng-model="item.question" type="text">
        <input ng-model="item.text" type="text" >
        <input ng-model="item.inlineChecked" type="checkbox" >
        <input ng-model="item.addendo1" type="number" >
        <input ng-model="item.addendo2" type="number" >
        <input ng-model="item.risultato" ng-value="item.addendo1+item.addendo2" class="colonnasmall">
    </div>
</div>

here is my JavaScript:

this.add = function() {
      vm.items.push({ 
          inlineChecked: false,
          question: "",
          text: "",
          addendo1 : 1,
          addendo2 : 2,
          risultato: addendo1+addendo2,
    });
  };

but this give me the error: ReferenceError: risultato is not defined.....

i changed then risultato to be=0 (on javascript),

and i changed the ng-model

<input ng-model="item.risultato" ng-value="item.addendo1+item.addendo2" class="colonnasmall">

to

<input ng-model="item.risultato=item.addendo1+item.addendo2" class="colonnasmall">

it works but gave me an error:

Error: ngModel:nonassign Non-Assignable Expression

anyone can help me?? thanks a lot


Solution

  • Use in JS (no need to add a default value):

    this.add = function() {
      vm.items.push({ 
          inlineChecked: false,
          question: "",
          text: "",
          addendo1 : 1,
          addendo2 : 2
    });
    };
    

    In HTML , remove ng-value naduse ng-change on both operands:

        <input ng-model="item.addendo1" type="number" ng-change="item.risultato = item.addendo1+item.addendo2" >
        <input ng-model="item.addendo2" type="number" ng-change="item.risultato = item.addendo1+item.addendo2" >
        <input ng-model="item.risultato"  class="colonnasmall">