Tonatiuh
Tonatiuh

Reputation: 2515

Best approach to manage related objects in angular?

Let's say I have two json objects, one of users and one of 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"}
]

So I have to loop accross all the users array, and for each of them get the account information. Which is the best way to manage those relationships for accessing them in the markup? I found the following solutions:

Approach 1: Make a repeat of only one element, so that it's just to filter the elements and to make it available in that 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 the information is returned from the backend, bringing a json of each user where each json is returned with the account information. But that will repeat a lot of informacion in each json object. Also this implies changing the backend because of angular.

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

Could someone tell me if those approachs are correct? Is there a better way to manage the object relationships in angular?

Thanks a lot.

Upvotes: 4

Views: 273

Answers (2)

MonoThreaded
MonoThreaded

Reputation: 12043

I faced the same problem and decided it was not the front-end job to perform data mapping.
So instead of returning on account_id like:

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

I extended the model with "account_name" (or whatever the equivalent for me)
Hence the suggested output

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 slightly redundant but makes your life easier in the UI and doesn't cost much in the server.

Upvotes: 0

jessegavin
jessegavin

Reputation: 75660

If you really don't like the thought of changing the shape of the data coming from the server, another option is to just map the 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];
      }
    }
  }


});

Upvotes: 3

Related Questions