单击类别链接时过滤项目列表 [英] filter list of items when clicking category link
问题描述
我有一个带有ng-repeat"的项目列表.每个项目都包含一个带有链接标题和链接类别的 div.单击类别时,我想过滤项目列表,以便它只显示属于该类别的项目.我怎样才能做到这一点?
到目前为止,我有一个项目列表:
<div class="title"><a href="{{link.url}}" target="_blank">{{link.title}}</a></div><div class="category_label" ng-click="filterCategory(link)>{{link.category }}</div>
在控制器中,我有一个函数filterCategory",它显示带有链接类别的警报.我有过滤器:?"我猜过滤器的价值必须来.这是控制器功能:
$scope.filterCategory = (link) ->警报(链接.类别)
知道如何进行吗?谢谢!
您可以在控制器范围内创建一个用于过滤的对象,并将其传递给 ng-repeat 中的
filter
表达式
var app = angular.module('app', []);app.controller('main', function($scope) {$scope.filters = { };$scope.links = [{名称:'苹果',类别:'水果'},{名称:'梨',类别:'水果'},{名称:'杏仁',类别:'坚果'},{名称:'芒果',类别:'水果'},{名称:'腰果',类别:'坚果'}];});
所以现在我们有一个 filters
对象附加到范围.如果得到category
的key,filter
表达式会根据对象是否有category
的key自动过滤对象,并且匹配.
有关更多详细信息,请查看过滤器文档的参数"部分.
因此您的 HTML 可能如下所示:
<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>
I have a list of items with "ng-repeat". Each item contains a div with a link title and link category. When clicking on a category, I want to filter the list of items, so that it only shows the items belonging to that category. how can I achieve that?
So far I have a list of items:
<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>
And in the controller I have a function "filterCategory" which shows an alert with the link category. And I have the "filter: ?" where I guess the value of the filter has to come. Ths is the controller function:
$scope.filterCategory = (link) ->
alert(link.category)
Any idea how to proceed? Thanks!
You can create an object on your controller's scope intended for filtering and pass it to the filter
expression in 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'}
];
});
So now we have a filters
object attached to the scope. If it gets a key of category
, the filter
expression will automatically filter the objects according to whether or not they have a key of category
and it matches.
For more details, look at the "Parameters" section of the filter docs.
So your HTML could look like:
<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.
这篇关于单击类别链接时过滤项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!