我有一个这样的对象:
Object {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 11, 6: 13, 7: 15, 8: 17, 9: 19, 10: 22, 11: 24, 12: 26, 13: 28, 14: 30, 15: 33, 16: 35, 17: 37, 18: 39, 19: 41, 20: 44, 21: 46, 22: 48, 23: 50, 24: 52, 25: 55, 26: 57, 27: 59, 28: 61, 29: 63, 30: 66, 31: 68, 32: 70, 33: 72, 34: 74, 35: 77, 36: 79, 37: 81, 38: 83, 39: 85, 40: 88, 41: 90, 42: 92, 43: 94, 44: 97, 45: 99, 46: 101, 47: 103, 48: 105, 49: 108, 50: 110, 51: 112, 52: 114, 53: 116, 54: 119, 55: 121, 56: 123, 57: 125, 58: 127, 59: 130, 60: 132, 61: 134, 62: 136, 63: 138, 64: 141, 65: 143, 66: 145, 67: 147, 68: 149, 69: 152, 70: 154, 71: 156, 72: 158, 73: 160, 74: 163, 75: 165, 76: 167, 77: 169, 78: 171, 79: 174, 80: 176, 81: 178, 82: 180, 83: 182, 84: 185, 85: 187, 86: 189, 87: 191, 88: 194, 89: 196, 90: 198, 91: 200, 92: 202, 93: 205, 94: 207, 95: 209, 96: 211, 97: 213, 98: 216, 99: 218…}
我正在选择框的ng-options中使用它。但是我按错误顺序渲染它们:
1
10
100
101
...
11
110
如何将选择框中的值排序为整数?通常,我应该使用自然排序功能。这样的事情https://github.com/overset/javascript-natural-sort/blob/master/naturalSort.js但是我在这个列表中只有数字,在我的情况下可能有更简单的解决方案吗?
也许有可能以某种方式使角度对象键和整数?
以下是plunkr:http://plnkr.co/edit/mUBM0egiS8pl8odaWQQY?p=preview
答案 0 :(得分:9)
您必须将列表转换为数组以保证排序顺序。 You cannot guarantee sort order using an Object hashmap, it just doesn't work that way.
最好的选择 - 性能明智 - 是转换控制器中的对象:
var values = {...}
$scope.selectOptions = [];
angular.forEach(values, function(value, key) {
$scope.selectOptions.push({
key: value,
label: key
});
});
$scope.selectOptions.sort(mySortingFunction);
在您看来:
<select model="selected" ng-options="opt.key as opt.label for opt in selectOptions"></select>
这将创建一个选择,其中标签是原始对象的属性键,值是原始对象的属性值。
如果您希望动态重新排列,可以将其作为过滤器进行,但要为潜在的性能问题做好准备。
app.filter("naturalSortedObject", function() {
return function(obj) {
var result = [];
angular.forEach(obj, function(value, key) {
result.push({
key: value,
label: key
});
});
result.sort(mySortingFunction);
return result;
}
});
然后像这样使用它:
<select model="selected"
ng-options="opt.key as opt.label for opt in selectOptions | naturalSortedObject"></select>
此外,您已经拥有了自然排序算法,但是如果您想要一个已经设计为used as an Angular filter & module, I wrote one的算法。它集成得非常好,并且可以以缓存方式使用,使其更快一些。
答案 1 :(得分:1)
你可以试试这个:
<强>的Javascript 强>
self.foo = []
angular.forEach [9..364], (i, el) ->
self.foo.push({ key: el, value: ~~(el / 0.45359237) })
<强> HTML 强>
<select ng-options="item.value as item.key for item in foo" ng-model="w"></select>