Angular ng-repeat - how to join or combine data from different arrays

Viewed 1488

I'm trying to join/combine two arrays in angular ng-repeat.

Simple example book/author where I want to print book titles with coresponding author name.

Books are in one array, authors in another.

How to join data in this example?

JSFiddle: http://jsfiddle.net/1jxsh0x3/

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {

  $scope.authors = [{
    id: "1",
    name: "John"
  }, {
    id: "2",
    name: "Peter"
  }, {
    id: "3",
    name: "Mark"
  }];
  
  $scope.books = [{
    id: "1",
    id_author: "3",
    name: "Book Lorem"
  }, {
    id: "2",
    id_author: "1",
    name: "Book Ipsum"
  }, {
    id: "3",
    id_author: "1",
    name: "Book Dark"
  }];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-controller="MyCtrl">
  <div ng-repeat="book in books">
    <div>Book title: {{book.name}}</div>
    <div>Authors name: {{authors[$index].name}}</div>
    <hr>
  </div>
</div>

8 Answers
Related