fubar92
fubar92

Reputation: 85

Create a dynamic table in Angular based on the amount of rows chosen in a drop down list

I am trying to learn AngularJS 1.6 and I am trying to populate a table with rows depending on the amount of rows selected in a dropdown list. It could be anywhere from 1 to 12. So far I have the following code.

 <body ng-controller="myController">
    <div>
        <p>Blue Corner Boxer: </p> <input type="text" ng-model="nameBlue">
        <br>
        <p>Red Corner Boxer: </p> <input type="text" ng-model="nameRed">
        <br>
        <p>Number of Rounds:</p> <select ng-model="selectedRounds"><option ng-repeat="x in rounds">{{x}}</option></select>
    </div>

    <div>
            <table class="table table-striped">
                    <thead>
                        <tr>
                            <th style="text-align:center">{{nameBlue}}</th>
                            <th style="text-align:center">Round</th>
                            <th style="text-align:center">{{nameRed}}</th>
                        </tr>
                    </thead>
                    <tbody class="tablerows">
                       <tr ng-repeat="x in selectedRounds">
                           <td>Test</td>
                           <td>Test</td>
                           <td>Test</td>
                       </tr>
                    </tbody>
                </table>

                <h2 style="text-align: center">Final Score: </h2> {{scoreBlue1 + ScoreBlue2}}
    </div>
</body>

Then in the js file

//Create the module
var myApp = angular.module("myModule", []);



//Create the controller and register the module in one line
myApp.controller("myController", function ($scope) {
    $scope.message = "AngularJS tutorial";
    $scope.score = [1,2,3,4,5,6,7,8,9,10];
    $scope.rounds = [1,2,3,4,5,6,7,8,9,10,11,12];
});

So far the table will add 1 row on selection of anything 1 to 9, but 10 to 12 adds 2 rows. So I think I am wondering how to create an array length of size "selectedrounds" that will repeat rows with the repeater.

Thanks

Upvotes: 3

Views: 367

Answers (1)

Iaroslav
Iaroslav

Reputation: 295

If you need an array only for iterating and you don't worry about data in it. You can do something like this:

In your controller:

$scope.selectedRounds = 0;
$scope.getRoundsArray(){
   return new Array($scope.selectedRounds);
}

We just create an array with needed length and with all elements are 'undefined'. If you create an array with 3 lenght you will get: ['undefined', 'undefined', 'undefined'].

In view:

<tr ng-repeat="x in getRoundsArray() track by $index">

You need this track by $index cause your array contains only 'undefined' values so to prevent angular arguing about duplicate keys we need to use track by.

Upvotes: 2

Related Questions