Frostbch Frostbch - 1 month ago 9
AngularJS Question

ng-repeat different values based on url

I am trying to repeat values from array of objects based on current url. Let's say that when my url is this "localhost/#/scores/javelin" i want to repeat only javelin scores from my array.

My array looks like this:

$scope.ppl =
[
{
firstname: 'Donald',
lastname: 'Trump',
from: 'USA',
run100m: ['1s','2s','3s'],
javelin: ['50m','20m','44m']
},
{
firstname: 'Foo',
lastname: 'Bar',
from: 'SWE',
run100m: ['1s','2s','3s'],
javelin: ['80m','10m','54m']
},
];


There will be over 15 type of sports and unknown amount of people. I have no idea how i can do this without making huge amounts of arrays. I've been trying all kinds of things to do this but nothing have not worked.

This is what my repeat looks like:

<tr ng-repeat="x in ppl">
<td>{{x.firstname}}</td>
<td>{{x.lastname}}</td>
<td>{{x.from}}</td>
<td><span ng-repeat="y in x.run100m track by $index">{{ y }}</span>
</td>
<td><button>edit</button></td>
</tr>


This code is working like this but only with run100m. If i change the url to /javelin, i want javelin scores inside of span.

Only way i can make this work is that i create

<span ng-show=" URL == javelin"></span>


etc. but i am not sure if that is so smart way. So my question is that how i can make this work smart way? the ppl structure doesn't have to be like that but it would be great if i can store all the information in 1 variable.

Oh and i forgot to say that i know how i can get url inside of controller. That is not the problem here.

So i want repeat based on this variable:

var path = $routeParams.sport;

Answer

Use a property accessor in the expression:

<tr ng-repeat="x in ppl">
    <td>{{x.firstname}}</td>
    <td>{{x.lastname}}</td>
    <td>{{x.from}}</td>
    <td><span ng-repeat="y in x[eventType] track by $index">{{ y }}</span>
    </td>
    <td><button>edit</button></td>
</tr>