我从新闻源REST API中获取了一些新闻,并实现了自由文本即时搜索。
我现在正尝试从下拉列表中实现搜索,该列表使用相同的数据但我可以按作者进行过滤。我如何使用下拉菜单与使用自由文本搜索作为ng-repeat
上的过滤器的方式相同,以便我可以按作者过滤结果?
app.js:
/* Newsfeed API Call */
var app = angular.module('newsFeed', [])
.controller('Newsfeed', function($scope, $http) {
$http.get('https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=6ddf8d3cc8a54cc0abf89ad7d685da54').
then(function(response) {
$scope.news = response.data;
console.log(response.data.articles);
});
});
的index.html:
<div class="container">
<br/>
<form>
<div class="col-md-6">
<h2>Newsfeed</h2>
<br/>
<div class="form-group">
<input type="text" class="form-control" ng-model="searchText" name="search-news" id="search-news" placeholder="Search for news">
</div>
<div class="form-group">
<select class="custom-select" ng-controller="Newsfeed">
<option selected>Filter by Author</option>
<option ng-repeat="n in news.articles | filter:searchAuthor | unique: 'author'" value="1">{{n.author}}</option>
</select>
</div>
</div>
</form>
<div ng-controller="Newsfeed">
<div class="card" style="width: 20rem;" ng-repeat="n in news.articles | filter:searchText | filter:searchAuthor">
<img class="card-img-top img-responsive" src="{{n.urlToImage}}" alt="Card image cap">
<div class="card-block">
<h4 class="card-title">{{n.title}}</h4>
<p class="card-text"> {{n.description | cut:true:100:' ...'}}</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
</div>
答案 0 :(得分:0)
我想您希望<select>
过滤您的ng-repeat
文章。
您可以使用ng-options
在<select>
上显示值,并使用ng-model
将所选值存储在范围内:
<select ng-options="n.author for n in news.articles | unique: 'author'" ng-model="selectedAuthor">
<option value="" ng-click="selectedAuthor = undefined">Filter by Author</option>
</select>
然后,您只需要在selectedAuthor
上过滤文章:
<div ng-repeat="n in news.articles | filter: searchText | filter: selectedAuthor">