filter list of items when clicking category link

前端 未结 2 1588
甜味超标
甜味超标 2020-12-13 07:30

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

相关标签:
2条回答
  • 2020-12-13 07:56

    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.

    0 讨论(0)
  • 2020-12-13 07:59

    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>

    0 讨论(0)
提交回复
热议问题