GluePear GluePear - 3 months ago 71
AngularJS Question

Using foreign key in ng-repeat

I have two tables:


  1. A jobs table with 3 fields:
    id
    ,
    client_id
    ,
    name
    .

  2. A clients table with 2 fields:
    id
    ,
    name
    .



Using Angular 1.5, I'm iterating over the jobs:

controller('JobsController', ['$scope', 'Job', 'Client', function($scope, Job, Client) {
$scope.jobs = Job.query();
$scope.clients = Client.query();
}]);


HTML:

<tr ng-repeat="job in jobs">
<td>
{{clients[job.client_id].name}}
</td>
<td>
{{job.name}}
</td>
</tr>


In the HTML the first column should be the client name. As it is, this isn't working, because
$scope.clients
is an array of objects that look a bit like this:

[{'id':4, 'name':'test_name'}, {'id':7, 'name':'another client'}]


Is there a way to pick from this
clients
array by
id
, in my
ng-repeat
loop?

$scope.jobs
looks like:

[{'id':100, 'client_id': 4, 'name': 'a job'}, ...]

Answer

To begin with, it may be easier to do the join on the server side, to where your $scope.jobs would look more like:

[
{
    'id': 100,
    'name': 'a job',
    'client': {
        'id': 4
        'name': 'test_name'
    }
} 
...
]

If you need to do it on the front end, what I would do is add a method to your controller to get the client for a specified job. Something like this:

$scope.getClientName = function(job) {
    //to prevent errors if $scope.clients is not loaded yet
    if (!$scope.clients) {
        return;
    }

    for (var c = 0; c < $scope.clients.length; c++) {
        var client = $scope.clients[c];
        if (client.id = job.client_id) {
            return client.name;
        }
    }
}

Then instead of {{clients[job.client_id].name}} call your function and pass in the job:

{{getClientName(job)}}