brohymn brohymn - 5 months ago 50
Javascript Question

Angular , 2 JSON endpoints loaded, 1 ngrepeat. how to replace 1 within the other?

I have 2 endpoints ( which I do not think they are related) from jsonplaceholder:

jsonplaceholder.typicode.com/todos

jsonplaceholder.typicode.com/users

In my angular app I can pull the todo items.
The todo items have a userId value.

I've loaded the 2 JSON objects with ngresource. If I use 2 ng-repeats I can pull todos and users separately, obviously.

So, the question is ...instead of those userId...can I replace them with the actual user names, eventough they might not be related or nested?

HTML

<tbody>
<tr ng-repeat="todo in todos ">
<td>{{todo.userId}}</td>
<td>{{todo.id.name}}</td>
<td>{{todo.title}}</td>
<td>{{todo.completed?'COMPLETED':'INCOMPLETE'}}</td>
<td> <button type="button" ng-click="UpdateTodo($index, true)" class="btn btn-info">Update</button> </td>
</tr>
</tbody>


My service

skillzApp.factory('Users', function($resource){
return $resource('h://jsonplaceholder.typicode.com/users/:user', {user:'@user'})
});


skillzApp.factory('UserTodos', function($resource) {
var data = $resource('h://jsonplaceholder.typicode.com/todos/:todo', {todo:'@todo'}, {
update: {
method: 'PUT'
}
});
return data;
});


Controller:

'use strict';

skillzApp.controller("SkillController", function ($scope, UserTodos, Users) {

$scope.todos = UserTodos.query();
$scope.users = Users.query();


$scope.UpdateTodo = function(index, value) {

$scope.todos[index].completed = value;



};

});


See pic, user name needs to be in blank space
Snapshot

Answer

The best thing for you to do would be, if you had a users table and a todos table in a database, to make a SELECT with JOINing on the tables and get the user name to come out as part of the todo list by referencing users to the todo userId.

Alternatively, if you're only using fixed JSON or javascript arrays, then you can do something like this:

<tbody>
  <tr ng-repeat="todo in todos ">
    <td>{{todo.userId}}</td>
    <td>{{::returnUserName(todo.userId)}}</td><!--Should give you the correct username.-->
    <td>{{todo.title}}</td>
    <td>{{todo.completed?'COMPLETED':'INCOMPLETE'}}</td>
    <td> <button type="button" ng-click="UpdateTodo($index, true)" class="btn btn-info">Update</button> </td>
 </tr>
</tbody>

And then for the javascript make a $scope variable:

$scope.users = [{id: 1, name:'John Doe'},{id:2, name:'Jane Appleseed'}];
$scope.returnUserName = function(userID) {
   var i, len;
   for (len = $scope.users.length, i=0; i<len; ++i) {
      if($scope.users[i].id == userID) {
         return $scope.users[i].name;
      }
   }
   return 'No user found.'
}