使用angularjs解析JSON,并选择select选项

Parsing JSON with angularjs with chosen select option

本文关键字:选择 select 选项 angularjs 解析 JSON 使用      更新时间:2023-09-26

我有两个url,我在其中调用两个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控制器.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中填充的,但我不确定如何从这里开始实现我想要做的事情

感谢您的阅读。

您可以使用过滤器

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

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

工作Fiddle:https://jsfiddle.net/U3pVM/14411/

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