Angular filter and order elements on click

前端 未结 1 621
逝去的感伤
逝去的感伤 2021-02-03 15:10

I\'m trying to filter a list of items (grabbed from JSON) onclick. I pull the data once from the server then would like to filter/order the elements using Angular.

Here

1条回答
  •  死守一世寂寞
    2021-02-03 15:58

    I would wrap the entire functionality inside a parent controller with the tab change and category select functions inside that parent controller (the child scopes will inherit this) so that the scope variables can be shared down for the filters and order By:

    Reading Materials on Controller Inheritance: http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller

    Demo: http://plnkr.co/edit/rh3wGYhuoHSHJEa4PoQi?p=preview

    HTML:

    • {{category.name}}
    • Recent items
    • Popular items

    {{item.title}} - {{item.date}}

    {{item.description}}

    View full item details

    Here is the parent controller:

    myApp.controller('ListController', function($scope, $route, $location, $http, Categories){
    
     $scope.sort = function(item) {
       if (  $scope.orderProp == 'date') {
            return new Date(item.date);
        }
        return item[$scope.orderProp];
      }
    
      $scope.sendCategory = function(category) {
        // How can I pass this value to ItemController?
         $scope.search =category.name;
      };
    
       $scope.orderProp='date';
    
        $scope.tab = function (tabIndex) {
         //Sort by date
          if (tabIndex == 1){
            //alert(tabIndex);
            $scope.orderProp='date';
    
          }   
          //Sort by views 
          if (tabIndex == 2){
            $scope.orderProp = 'views';
          }
    
       };
    
    })
    

    ** Update **

    I've updated the controller to sort the dates correctly since they need to be parsed first.

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