lonewarrior556
lonewarrior556

Reputation: 4479

Can ng-model update another ng-model?

This is my code:

<table ng-init="liveTotal={}">
  <tr ng-repeat="x in sovCtrl.topics" >
    <td> {{x}}</td>
    <td><input ng-model="sovCtrl.objects[x]" type="number"></td>
    <td ng-hide="true">
        <input ng-model="liveTotal[$index]" type="number" value="{{sovCtrl.objects[x]}}">
    </td>
  </tr>
</table>

<div > Current Result:
  {{ 0 + liveTotal[0] + liveTotal[1] + liveTotal[2] + liveTotal[3] + liveTotal[4]}} 
</div>

What I'm trying to do is have a live result of the sum of all the Inputted topic values(there will never be more than 5) without using $scope or any extra sovCtrl methods/objects or adding a script; The topics are strings I can't predict.

The 2nd input CHANGES when I type into the first input, but the result in the div does not. The result in the div changes only when I type or press on the 2nd input(if I make it visible)

Can this be done using angular but modifying only the above HTML?

Edit: sovCtrl.objects gets passed into functions that graph the values. Modifying the the keys would break those functions.

Upvotes: 0

Views: 88

Answers (2)

lonewarrior556
lonewarrior556

Reputation: 4479

Got it, this works.

<table ng-init="liveTotal={}">
  <tr ng-repeat="x in sovCtrl.topics" >
    <td> {{x}}</td>
    <td><input ng-model="sovCtrl.objects[x]" type="number"></td>
    <td ng-show="false"> {{ liveTotal[$index]= sovCtrl.shareOfVoice[x]}}</td>
  </tr>
</table>

<div > Current Result:
 {{ 0 + liveTotal[0] + liveTotal[1] + liveTotal[2] + liveTotal[3] + liveTotal[4]}} 
</div>

Upvotes: 0

techblu3
techblu3

Reputation: 170

Why don't you directly do something like shown below wherein you directly use the first input You just add an index (which is provided in ng-repeat of any variable) and now you can access values by using index 0,1,2,3,4

<table ng-init="liveTotal={}">
    <tr ng-repeat="(i,x) in sovCtrl.topics" >
        <td> {{x}}</td>
        <td><input ng-model="sovCtrl.objects[x]" ng-change="sovCtrl.objects_yo[i]=sovCtrl.objects[x]" type="number"></td>
    </tr>
</table>

<div> Current Result:
    {{ 0 + sovCtrl.objects_yo[0] + sovCtrl.objects_yo[1] + sovCtrl.objects_yo[2] + sovCtrl.objects_yo[3] + sovCtrl.objects_yo[4]}}
</div>

Upvotes: 1

Related Questions