2013-02-14 46 views
20

我有一個「ng-repeat」項目列表。每個項目都包含一個帶鏈接標題和鏈接類別的div。當點擊一個類別時,我想過濾項目列表,以便它只顯示屬於該類別的項目。我怎麼能做到這一點?當點擊分類鏈接時過濾項目列表

到目前爲止,我有一個項目列表:

<div class="link_line" ng-repeat="link in links | filter: ? "> 
    <div class="title"><a href="{{link.url}}" target="_blank">{{link.title}}</a></div> 
    <div class="category_label" ng-click="filterCategory(link)>{{ link.category }}</div> 
    </div> 

而在控制器我有一個功能「filterCategory」,這顯示了鏈接類別警報。我有「過濾器:?」在那裏我猜測過濾器的價值已經到來。這是控制器功能:

$scope.filterCategory = (link) -> 
    alert(link.category) 

任何想法如何進行?謝謝!

回答

46

您可以創建用於過濾功能控制器的範圍對象,並把它傳遞給filter表達ng-repeat

var app = angular.module('app', []); 

app.controller('main', function($scope) { 
    $scope.filters = { }; 

    $scope.links = [ 
     {name: 'Apple', category: 'Fruit'}, 
     {name: 'Pear', category: 'Fruit'}, 
     {name: 'Almond', category: 'Nut'}, 
     {name: 'Mango', category: 'Fruit'}, 
     {name: 'Cashew', category: 'Nut'} 
    ]; 
}); 

所以現在我們有連接到範圍filters對象。如果得到category的密鑰,則filter表達式將根據它們是否具有密鑰category並且它匹配來自動過濾對象。

有關更多詳細信息,請參閱filter docs的「參數」部分。

所以你的HTML可能看起來像:

<div class="link_line" ng-repeat="link in links | filter:filters"> 
    <div class="title"><a href="{{link.url}}" target="_blank">{{link.title}}</a></div> 
    <div class="category_label" ng-click="filters.category = link.category">{{ link.category }}</div> 
</div> 

Here's a quick fiddle of this in action

+0

我需要類似的東西和你的回答對我幫助很大!我不得不改變它,所以它支持多個類別的每個項目,這就是我想出來的:http://jsfiddle.net/xffe9zwp/ – Alex 2015-10-29 10:32:01

+0

如果$ scope.links有int值,我如何篩選其中的值?例如:「5> = && 10 <=」 – sanjeewa 2017-06-23 07:34:00

1

angular.module('app',[]) 
 
    .controller('MainController', function($scope) { 
 
    $scope.team =[ 
 
    {cat_id:1,team: 'alpha'}, 
 
    {cat_id:2,team: 'beta'}, 
 
    {cat_id:3,team: 'gamma'} 
 
       ]; 
 
    
 
    $scope.players = [ 
 
     {name: 'Gene',cat_id : 1}, 
 
     {name: 'George',cat_id : 2}, 
 
     {name: 'Steve',cat_id : 3}, 
 
     {name: 'Pzula',cat_id : 2}, 
 
     {name: 'shrikant',cat_id : 3} 
 
    ]; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="MainController"> 
 
    
 
<ul ng-repeat="(key, value) in team "> 
 
{{value.team}} 
 
    
 
<li ng-repeat="p in players " ng-if="p.cat_id==value.cat_id"> 
 
    {{ p.name }} 
 
</li> 
 
    
 
</ul> 
 
</div>