0

I have two urls where I call two json objects.

authors.json

[
    {
    "id":"1",
    "name":"Dan Brown",
    },
    {
    "id":"2",
    "name":"Steve Gates",
    }
]

books.js

[
    {
    "id":"1",
    "author_id":"1",
    "bookname":"Advance Programming"
    },
    {
    "id":"2",
    "author_id":"1",
    "bookname":"Advanced Programming"
    },
    {
    "id":"3",
    "author_id":"1",
    "bookname":"C++ involved beyond 1"
    },
    {
    "id":"4",
    "author_id":"1",
    "bookname":"C++ involved beyond 2"
    },
    {
    "id":"5",
    "author_id":"2",
    "bookname":"C++ involved beyond 3"
    },
    {
    "id":"6",
    "author_id":"2",
    "bookname":"Java involved beyond"
    }
]

What I am trying to achieve is to display a list of all books for chosen author from selected dropdown.

So far my HTML looks something like this.

<div ng-controller="authorSelectController">
    <select class="form-control" id="authors" ng-model="selectedAuthor">
        <option value="0" selected="selected">- Select Author -</option> 
        <option ng-repeat="author in authors" value="{{author.id}}">{{author.name}}</option>
    </select>

    <div ng-model="showBooks">
        //Show a list of books here
    </div>
</div>

my JS controller.js

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

myApp.controller('authorSelectController', ['$scope', '$http', function($scope, $http) {
    $http.get('../assets/js/data/authors.json').success(function(data) {
        $scope.authors = data;
    });
}]);

Currently the authors get populate from the json, however I am unsure how to proceed from here to achieve what I want to do.

Thank you for reading.

1 Answer 1

1

You can use filter

 <div ng-repeat="book in books | filter:{'author_id':selectedAuthor}">
        {{book.id}} :: {{book.bookname}}
 </div>

In the above code books is the array of all the books and selectedAuthor the selected author ID.

Working Fiddle : https://jsfiddle.net/U3pVM/14411/

EDIT: If you also want to display the author name one way of doing it is storing the authorName globally in one variable and updating it whenever the dropdown value is changed using ng-change .
Fiddle : https://jsfiddle.net/U3pVM/14415/

Sign up to request clarification or add additional context in comments.

4 Comments

but how and when do I call the second json?
@BaconJuice You can just store the whole json directly and it would be filtered accordingly using filter
@BaconJuice Check the updated answer ... I added a working fiddle
hi @maandoo, just a follow up question. What is I wanted to show the Author along with the book id and book name as well? 1 :: Advance Programming :: Dan Brown

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.