Best approach to managing related objects in angular?

Let's say I have two json objects, one of the users and one of the accounts, something like:

users = [ {id: 1, account_id: 1}, {id: 2, account_id: 2}, {id: 3, account_id: 1} ] accounts = [ {id: 1, name: "administrator"}, {id: 2, name: "moderator"} ] 

Thus, I need to iterate over all arrays of users and each of them gets account information. What is the best way to manage these relationships to access them in markup? I found the following solutions:

Approach 1: Repeat only one element, so that it simply filters out the elements and makes them available in this part of the markup

 <div ng-repeat="user in users"> <div ng-repeat="account in getAccountFromId(user.account_id)"> <!-- now account is available in all this scope to access user.account.name --> </div> </div> 

Approach 2: change the way information is returned from the backend, resulting in a json for each user, where each json is returned with account information. But this will repeat a lot of information in every json object. This also implies a change in the backend due to angular.

 <div ng-repeat="user in users"> <!-- with this approach I can access here user.account.name --> </div> 

Can someone tell me if these approaches are correct? Is there a better way to manage object relationships in angular?

Thank you very much.

+4
source share
2 answers

If you really don't like the idea of ​​changing the form of the data coming from the server, another option is to simply map users to accounts in javascript.

 app.controller("MyController", function($scope) { // Pretend that 'users' and 'accounts' here came from an xhr request var users = [ {id: 1, account_id: 1}, {id: 2, account_id: 2}, {id: 3, account_id: 1} ] var accounts = [ {id: 1, name: "administrator"}, {id: 2, name: "moderator"} ] // Map accounts to users for(var i=0; i<users.length; i++) { for(var j=0; j<accounts.length; j++) { if (accounts[j].id === users[i].account_id) { users[i].account = accounts[j]; } } } }); 
+3
source

I ran into the same problem and decided that an external job should not be performed to perform data mapping.
Therefore, instead of returning to account_id like:

 users = [ {id: 1, account_id: 1}, {id: 2, account_id: 2}, {id: 3, account_id: 1} ] 

I expanded the model with "account_name" (or any other equivalent for me)
Consequently, the proposed conclusion

 users = [ {id: 1, account_id: 1, account_name: "administrator"}, {id: 2, account_id: 2, account_name: "moderator"}, {id: 3, account_id: 1, account_name: "administrator"} ] 

It is a little redundant, but makes your life easier in the user interface and does not cost much on the server.

0
source

Source: https://habr.com/ru/post/1482589/


All Articles