繁体   English   中英

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

[英]Angular JS live select dropdown search filter

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

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

这是一个JSFiddle

应用程序.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);
        });
    });

索引.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>

我猜您希望您的<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">

工作 JSFiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM