Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

angularjs - filter list of items when clicking category link

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...