gpt4 book ai didi

javascript - 如何使用 angularjs 自定义排序这些数据?

转载 作者:行者123 更新时间:2023-12-03 03:10:36 25 4
gpt4 key购买 nike

我的 HTML 文件

 <div ng-controller="MyCtrl">    
<input type="text" ng-model="searchText" />
<ul ng-repeat="strVal in arrVal|filter:searchText|mySort" >
<li>{{strVal}}</li>
</ul></div>

我的js文件

var app=angular.module('myApp', []);
app.controller('MyCtrl', function ($scope,$filter) {
$scope.arrVal = ['six','one','two','five','three','four'];
});

app.filter('mySort', function() {
return function(input) {
return input.sort();
}
});

但结果是,我不想输出这个结果

five//but it is order by A-Z, I am very unhappy 
four
one
six
three
two

我希望这是我的最终输出结果,任何想法

one
two
three
four
five
six

知道如何做到这一点,非常感谢

Fiddle

最佳答案

你必须将你的单词转换为数字,我找到了这个SO Post并让这个工作像

app.filter('mySort', function() {

var Small = {
'zero': 0,
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9,
'ten': 10,
'eleven': 11,
'twelve': 12,
'thirteen': 13,
'fourteen': 14,
'fifteen': 15,
'sixteen': 16,
'seventeen': 17,
'eighteen': 18,
'nineteen': 19,
'twenty': 20,
'thirty': 30,
'forty': 40,
'fifty': 50,
'sixty': 60,
'seventy': 70,
'eighty': 80,
'ninety': 90
};

var Magnitude = {
'thousand': 1000,
'million': 1000000,
'billion': 1000000000,
'trillion': 1000000000000,
'quadrillion': 1000000000000000,
'quintillion': 1000000000000000000,
'sextillion': 1000000000000000000000,
'septillion': 1000000000000000000000000,
'octillion': 1000000000000000000000000000,
'nonillion': 1000000000000000000000000000000,
'decillion': 1000000000000000000000000000000000,
};

var a, n, g;

function text2num(s) {
a = s.toString().split(/[\s-]+/);
n = 0;
g = 0;
a.forEach(feach);
return n + g;
}

function feach(w) {
var x = Small[w];
if (x != null) {
g = g + x;
}
else if (w == "hundred") {
g = g * 100;
}
else {
x = Magnitude[w];
if (x != null) {
n = n + g * x
g = 0;
}
else {
alert("Unknown number: "+w);
}
}
}

return function(input) {
console.log(input);
return input.sort(function(a, b) {
return text2num(a) - text2num(b);
});
}
});

Working fiddle

关于javascript - 如何使用 angularjs 自定义排序这些数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46968355/

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