wagnerdelima wagnerdelima - 3 months ago 13
AngularJS Question

Two way data binding with dynamic table and angularjs?

I am creating a table where I will have dynamic row creation. Everytime user clicks a button, a new row is created, as follows:

angular

The second column will contain the amount of products. So, I'd like to sum all values from second column to display them with two-way data binding, using bg-model and ng-bind. Thus when user types in one, the valus will automatically update. I have no clue about it, in that the rows are dynamic!

For a fixed number of elements it works, but I dunno for a dynamic generation. Help?

Answer

We need to initially setup an object to use and perhaps put in some example data

 $scope.ourTableArray = [];
 $scope.ourTableArray.push({'textColumn': 'example text', 'valueColumn': 10});

Because of the way that Angular works with data-binding we can bind the ng-repeat of the table row to an array that will contain all of our values:

<tr ng-repeat="row in ourTableArray">
   <td><input type="text" ng-model="row.textColumn"</td>
   <td><input type="number" ng-model="row.valueColumn"</td>
</tr>

Next we need a way to add rows, so we can do that by creating a function to call on ng-click from some button. This will populate our $scope.ourTableArray following the format that was used in the first example value that we hardcoded in.

$scope.addRow = function(){
   $scope.ourTableArray.push({'textColumn': '', 'valueColumn': 0});
}

Now that the ng-repeat is set up we just need to have a way to calculate the values. The solution to that is by creating a function to sum up our valueColumn from our object:

$scope.calculateTotal = function() {
   var count = 0;
   for(row in $scope.ourTableArray){
      count += $scope.ourTableArray[row].valueColumn;
   }
   return count;
}

To output our new total all we have to do is call this function within our page.

Current Total of 2nd column: {{calculateTotal()}}

To summarize: Like I had stated above, because we have the ng-repeat binded to our array, anytime we modify the array (either by adding a row, removing a row, editing a rows values) it will be reflected immediately within the table. In addition, since we are outputting the results of our $calculateTotal() function, anytime we modify one of the values within our array it will also change.

Codepen Example: http://codepen.io/lliberacki/pen/mAdWBV