AngularJS 带参数的动态排序函数
AngularJS dynamic sort function with parameters
基于我尝试实现一个带参数的动态排序功能。它无法正常工作,因为正在调用默认排序。我怎样才能让它不调用默认的按名称排序?
我有 2 个按钮来调用函数和发送参数。
<button ng-click="dynamicOrder('f9.id')" class="btn">Sort by rating</button>
<button ng-click="dynamicOrder('name')" class="btn">Sort alphabetic</button>
我的 ng-repeat 看起来像这样:
<li ng-repeat="item in cumulus.items | orderBy: dynamicOrder()"
ng-show="cumulus.items.length > 0" class="block-grid-item">
<p>
<a target="_blank" href="{{ item.image }}">
<img class="img-responsive" src="{{ item.thumb }}">
</a>
</p>
<p style="overflow: hidden;">{{ item.name }}</p>
<p class="text-primary"><input type="hidden" value="{{ item.f9.id }}" /> {{ item.f9.displaystring }}</p>
</li>
和我的订单功能
$scope.dynamicOrder = function (sortParam) {
if (!sortParam) {
return 'name';
} else {
console.log("sortParam: ", typeof (sortParam), sortParam);
return sortParam;
}
};
orderBy
表达式可以是 getter 函数。此函数将以每个项目作为参数调用,return 值将用于排序。
$scope.getterFn = function(item) {
if ($scope.dynamicOrder == 'f9.id') {
return item.f9.id;
} else if ($scope.dynamicOrder == 'name') {
return item.name;
} else {
return item;
}
};
用法:
<button ng-click="dynamicOrder = 'f9.id'" class="btn">Sort by rating</button>
<button ng-click="dynamicOrder = 'name'" class="btn">Sort alphabetic</button>
<li ng-repeat="item in cumulus.items | orderBy: getterFn">
<!-- ... -->
</li>
有关详细信息,请参阅
基于
我有 2 个按钮来调用函数和发送参数。
<button ng-click="dynamicOrder('f9.id')" class="btn">Sort by rating</button>
<button ng-click="dynamicOrder('name')" class="btn">Sort alphabetic</button>
我的 ng-repeat 看起来像这样:
<li ng-repeat="item in cumulus.items | orderBy: dynamicOrder()"
ng-show="cumulus.items.length > 0" class="block-grid-item">
<p>
<a target="_blank" href="{{ item.image }}">
<img class="img-responsive" src="{{ item.thumb }}">
</a>
</p>
<p style="overflow: hidden;">{{ item.name }}</p>
<p class="text-primary"><input type="hidden" value="{{ item.f9.id }}" /> {{ item.f9.displaystring }}</p>
</li>
和我的订单功能
$scope.dynamicOrder = function (sortParam) {
if (!sortParam) {
return 'name';
} else {
console.log("sortParam: ", typeof (sortParam), sortParam);
return sortParam;
}
};
orderBy
表达式可以是 getter 函数。此函数将以每个项目作为参数调用,return 值将用于排序。
$scope.getterFn = function(item) {
if ($scope.dynamicOrder == 'f9.id') {
return item.f9.id;
} else if ($scope.dynamicOrder == 'name') {
return item.name;
} else {
return item;
}
};
用法:
<button ng-click="dynamicOrder = 'f9.id'" class="btn">Sort by rating</button>
<button ng-click="dynamicOrder = 'name'" class="btn">Sort alphabetic</button>
<li ng-repeat="item in cumulus.items | orderBy: getterFn">
<!-- ... -->
</li>
有关详细信息,请参阅