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