Angular JS实时选择下拉搜索过滤器

时间:2017-01-26 13:11:37

标签: javascript angularjs angularjs-scope full-text-search html-select

我从新闻源REST API中获取了一些新闻,并实现了自由文本即时搜索。

我现在正尝试从下拉列表中实现搜索,该列表使用相同的数据但我可以按作者进行过滤。我如何使用下拉菜单与使用自由文本搜索作为ng-repeat上的过滤器的方式相同,以便我可以按作者过滤结果?

这是JSFiddle

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>

1 个答案:

答案 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">

Working JSFiddle