How to use natural sorting in ng-options?

前端 未结 2 1394
时光取名叫无心
时光取名叫无心 2021-01-21 16:22

I have an object like this:

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:          


        
相关标签:
2条回答
  • 2021-01-21 16:38

    You have to convert the list to an array to guarantee sort order. You cannot guarantee sort order using an Object hashmap, it just doesn't work that way.

    The best bet — performance wise — is to convert the object in the controller:

    var values = {...}
    $scope.selectOptions = [];
    angular.forEach(values, function(value, key) {
        $scope.selectOptions.push({
            key: value,
            label: key
        });
    });
    $scope.selectOptions.sort(mySortingFunction);
    

    In your view:

    <select model="selected" ng-options="opt.key as opt.label for opt in selectOptions"></select>
    

    This will create a select where the labels are the original object's property keys and the values are the original object's property values.

    If you want the rearranging to occur on the fly, you can do it as a filter, but be prepared for potential performance issues.

    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;
        }
    });
    

    Then use it like this:

    <select model="selected"
        ng-options="opt.key as opt.label for opt in selectOptions | naturalSortedObject"></select>
    

    Also, you already have a natural sorting algorithm, but if you want one that's already designed to be used as an Angular filter & module, I wrote one. It integrates pretty well, and can be used in a caching manner to make it a little faster.

    0 讨论(0)
  • 2021-01-21 16:46

    You can try this:

    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>
    
    0 讨论(0)
提交回复
热议问题