Angular filter and order elements on click

。_饼干妹妹 提交于 2019-12-03 08:46:30

问题


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 is my plunker: http://plnkr.co/edit/glSz1qytmdZ9BQfGbmVo?p=preview

  1. Tabs -- How could I filter/sort the items onclick? "Recent" would be sorted by date and "Popular" would be sorted by views.
  2. Categories -- I'm using ng-click to grab the category value although not sure how to update the filter dynamically (using the value passed onclick).

Thanks


回答1:


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:

<div ng-controller="ListController">
<div class="categories" ng-controller="CategoryController">
  <ul ng-repeat="category in categories">  
    <li ng-click="sendCategory(category)">{{category.name}}</li>
  </ul>
</div>

<div class="tabs" ng-controller="tabsController">
  <ul>
      <li ng-click="tab(1)">Recent items</li>
      <li ng-click="tab(2)">Popular items</li>
  </ul>
</div>

<div class="container">
  <div class="left" ng-controller="ItemController">
    <div class="itemList">
        <div class="item" ng-repeat="item in items | filter:search | orderBy:sort"> 
            <h3 ng-click="viewDetail(item)">{{item.title}} - {{item.date}}</h3>
            <p>{{item.description}}</p>
        <a ng-click="viewDetail(item)">View full item details</a>
        </div>
    </div>
  </div>
</div>
</div>

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.



来源:https://stackoverflow.com/questions/16334722/angular-filter-and-order-elements-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!