BaconJuice
BaconJuice

Reputation: 3769

Parsing JSON with angularjs with chosen select option

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.

Upvotes: 0

Views: 363

Answers (1)

Srinath Mandava
Srinath Mandava

Reputation: 3462

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/

Upvotes: 1

Related Questions