gpt4 book ai didi

javascript - Angularjs orderby 切换和删除 orderby

转载 作者:行者123 更新时间:2023-11-30 11:52:54 29 4
gpt4 key购买 nike

所以我尝试使用angularjs的orderby函数。目前我有一个原始数据集。

    $scope.customers = [
{"name" : "Bottom-Dollar Marketse" ,"city" : "Tsawassen"},
{"name" : "Alfreds Futterkiste", "city" : "Berlin"},
{"name" : "Bon app", "city" : "Marseille"},
{"name" : "Cactus Comidas para llevar", "city" : "Buenos Aires"},
{"name" : "Bolido Comidas preparadas", "city" : "Madrid"},
{"name" : "Around the Horn", "city" : "London"},
{"name" : "B's Beverages", "city" : "London"}
];

$scope.reverse= false;

$scope.toggleOrder = function(){
$scope.reverse=!$scope.reverse;

}

如果我使用以下内容来显示我的客户,我将获得按城市反向排序的数组。目前,如果需要,我可以单击切换按钮并反转数组。

 <button ng-click="toggleOrder()">ToggleReverse</button >

<li ng-repeat="x in customers | orderBy : 'city': reverse">{{x.name + ", " + x.city}}</li>

但现在的问题是我是否根本不需要 orderBy 函数。如果我想在没有任何订单的情况下获取我的原始客户数据,我该如何使用相同的 toggleOrder 函数来实现?

例如,当我加载数据时,它将是原始数组。如果第一次单击 toggleOrder 按钮,它将根据城市排序,第二次单击 toggleOrder 按钮将对城市进行反向排序,第三次单击 toggleOrder 按钮将没有排序并给我原始数组,依此类推。

如果 orderBy 函数不是最好的选择,请告诉我。

任何帮助都会很棒!

最佳答案

我不确定您为什么要在您的应用程序中添加此功能,但现在开始吧:

(function() {
'use strict';

angular
.module('app', [])
.constant('BUTTON_VALUES', {
1: 'Ascending',
2: 'Descending',
3: 'No order',
})
.controller('MainCtrl', MainCtrl);

MainCtrl.$inject = ['$scope', 'BUTTON_VALUES'];

function MainCtrl($scope, BUTTON_VALUES) {
$scope.customers = [
{
"name": "Bottom-Dollar Marketse",
"city": "Tsawassen"
},
{
"name": "Alfreds Futterkiste",
"city": "Berlin"
},
{
"name": "Bon app",
"city": "Marseille"
},
{
"name": "Cactus Comidas para llevar",
"city": "Buenos Aires"
},
{
"name": "Bolido Comidas preparadas",
"city": "Madrid"
},
{
"name": "Around the Horn",
"city": "London"
},
{
"name": "B's Beverages",
"city": "London"
}
];

$scope.btnValue = BUTTON_VALUES[3];
$scope.reverse = true;
$scope.orderParam = '';
var increment = 0;

$scope.toggleOrder = function() {
increment++;
$scope.btnValue = BUTTON_VALUES[increment];
switch (increment) {
case 1:
case 2:
$scope.orderParam = 'city';
$scope.reverse = !$scope.reverse;
break;
case 3:
$scope.orderParam = '';
increment = 0;
break;
}
}
}
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-controller="MainCtrl">
<button ng-click="toggleOrder()">{{btnValue}}</button>
<pre ng-bind-template="Order - {{orderParam}}"></pre>
<pre ng-bind-template="Reverse? {{reverse}}"></pre>
<hr>
<li ng-repeat="x in customers | orderBy : orderParam: orderParam && reverse">{{x.name + ", " + x.city}}</li>
</body>

</html>

注意:我添加了一个常量作为示例来演示如何处理您的按钮名称

希望对你有帮助。

关于javascript - Angularjs orderby 切换和删除 orderby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38947918/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com