Question

I have a simple ng-repeat that loops through a JSON file with a list of countries and details about that country e.g. currency, population for a particular set of months (24 in this case)

My ng-repeat loops through the first 12 months successfully, and displaying the corresponding text when the ng-switch criteria is met.

The issue i am facing, is that for some countries, we there is less than 12months worth of data, in some cases, only 3 months.

What i am struggling to do, is that if there is not sufficient data available, to display an empty cell.

Here's my ng-repeat:

<tr ng-repeat="country in Countries[key]">
    <th>{{country.countryName}}</th>

    <td ng-repeat="countryDetails in country.Details.slice(0, 12)" ng-switch="countryDetails.Population">
        <span ng-switch-when="10000">Medium</span>
        <span ng-switch-when="20000">Large</span>
        <span ng-switch-when="30000">Larger</span>
        <span ng-switch-when="40000">Very Large</span>
        <span ng-switch-default>Error</span>
    </td>
</tr>

Thanks

Was it helpful?

Solution

I created a fiddle similar to your case and fixed it like this:

<td ng-repeat="countryDetails in country.Details.slice(0, 12)" 
ng-switch="countryDetails">
    <span ng-switch-when="11">Medium</span>
    <span ng-switch-when="22">Large</span>
    <span ng-switch-when="33">Larger</span>
    <span ng-switch-when="44">Very Large</span>
    <span ng-switch-default>Error</span>
</td>
<td ng-repeat="emptyCell in getEmptyCells(country.Details.length)">
    empty
</td>

JS

$scope.getEmptyCells = function(len){
    var emptyCells = [];
    for(var i = 0; i < 12 - len; i++){
        emptyCells.push(i);
    }        
    return emptyCells;
}

Fiddle

OTHER TIPS

You can create a custom range in your scope:

$scope.range = function(n) {
    return new Array(n);
};

And then loop with it on your country.Details array

<td ng-repeat="a in range(12) track by $index" ng-switch="country.Details[ $index ].Population">
    <span ng-switch-when="10000">Medium</span>
    <span ng-switch-when="20000">Large</span>
    <span ng-switch-when="30000">Larger</span>
    <span ng-switch-when="40000">Very Large</span>
    <span ng-switch-default>Error</span>
</td>

Hi here is a fiddle which may help you Fiddle

<tr ng-repeat="details in countries.Details">

                <td ng-repeat="detail in details">{{detail}}</td>
            <td ng-if="details.length<12" ng-repeat="empty in getTempArray(details.length) track by $index">{{empty}}</td>      


      </tr>

I am not sure if I understood correctly, but I had some problems while using ng-repeat. If your array may have duplicate values then you should track by $index.

Try writing inside ng-repeat countryDetails in country.Details.slice(0, 12) track by $index instead of countryDetails in country.Details.slice(0, 12)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top