使用选择了选项的angularjs解析JSON

时间:2015-03-27 19:00:43

标签: javascript jquery json angularjs

我有两个网址,我称之为两个json对象。

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"
    }
]

我想要实现的是从所选下拉列表中显示所选作者的所有书籍列表。

到目前为止,我的HTML看起来像这样。

<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>

我的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;
    });
}]);

目前作者从json填充,但我不确定如何从这里开始实现我想做的事。

感谢您的阅读。

1 个答案:

答案 0 :(得分:1)

您可以使用filter

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

在上面的代码中,books是所有图书的数组,selectedAuthor是所选作者ID。

工作小提琴:https://jsfiddle.net/U3pVM/14411/

编辑:如果您还想显示作者姓名,一种方法是将authorName全局存储在一个变量中,并在使用ng-change更改下拉列值时更新它。
小提琴:https://jsfiddle.net/U3pVM/14415/