我正在尝试过滤一个项目列表(从JSON抓取)onclick。我从服务器提取数据一次,然后想使用Angular过滤/排序元素。
这是我的傻瓜:http://plnkr.co/edit/glSz1qytmdZ9BQfGbmVo?p=preview
由于
答案 0 :(得分:12)
我会将整个功能包装在父控制器中,并使用该父控制器内的选项卡更改和类别选择功能(子范围将继承此内容),以便可以为过滤器共享范围变量并按顺序排序: / p>
阅读有关Controller继承的资料:http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller
演示: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>
这是父控制器:
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';
}
};
})
**更新**
我已更新控制器以正确排序日期,因为它们需要先解析。