0

Let me preface by saying I'm fairly new to Node and Angular.

I have two models, one for items, and another for users. My items model has an "owner" attribute which is the id of the user which created it. I have a angular controller for handling the items. In the items controller, I would like to create a function which accepts a user id and returns the associated username. Now, I have tried doing this two ways. One was making the list of users as resource and passing it to the items controller. I have also tried adding this code to the users server route and adding a corresponding $http.get in the user controller.

app.route('/users/:userId')
    .get(users.read);

app.param('userId', users.userByID);

I'm not sure which approach I should be using, and I run into trouble as soon as I attempt to ng-repeat the items in the view corresponding to the items controller, while calling my function on every "owner" attribute. I have been binding my data to $scope.ownerName. Thanks for any advice.

0

1 Answer 1

2

Maybe you can use some kind of populate function like Mongoose does (http://mongoosejs.com/docs/populate.html). In your case item to user is a 1 to many relationship. Each item does have one owner user and each user can have many items. Assuming your models item and user are also used on server side I would provide a server side method to populate a list of items and replace the owner field with the corresponding user. For example

items = [{id:"item1",owner:"user1"},{id:"item2",owner:"user2"}]

populated with

users = [{id:"user1",username:"user A"},{id:"user2",username:"user B"}]

results into

items = [
  {id:"item1",owner:{id:"user1",username:"user A"}},
  {id:"item2",owner:{id:"user2",username:"user B"}}
]

Then you can just access username of owner by calling

items[0].owner.username
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.