AngularJS: mix data from two JSON files
For a web app, I am loading data from two JSON files using AngularJS. I can output both file data to my HTML, but I need to find a way to use the data from the first file ( posts.json
) for the address of the second ( users.json
).
Example for posts.json
:
{
"title": "Some topic",
"thread_id": 111,
"messages": [
{
"user_id": 123,
"message": "Hello, I'm Jim"
},
{
"user_id": 987,
"message": "Hi Jim, I'm Bob"
},
]
}
Example for users.json
:
[
{
"123": {
"name": "Jim",
"location": "London",
"website": "http://j.im"
}
},
{
"987": {
"name": "Bob",
"location": "New York",
"website": "http://b.ob"
}
}
]
A simple HTML example might look like this:
<p ng-repeat="talk in talks.messages">{{talk.name}} says {{talk.message}}</p>
However, I would also like to add some user metadata in the block ng-repeat
, for example associate a username with their site.
Or put it in a poorly formed expression, something like this:
<a href="{{{{talk.user_id}}.website}}">{{talk.name}}</a>
source to share
You can create a mapping object in your controller or directive. Something like:
.directive('myDirective', function($scope, _) {
$scope.posts = /* load your posts */
$scope.users = /* load your users */
$scope.usersById = _.indexBy($scope.users, 'id')
})
Then you will use it in your template, for example:
<p ng-repeat="talk in talks.messages">
{{talk.title}} by {{usersById[talk.user_id].name}}
</p>
source to share