Search code examples
javascriptangularjsangularjs-ng-repeatangularjs-orderby

AngularJS list items alphanumerically


I've been working on sorting a list of items alphanumerically. I have found that using ng-repeat with orderBy tends to sort either numerically or alphabetically depending on the type of data it is working with. It does not however sort alphanumerically.

JavaScript Code:

    function AppCtrl($scope) {
        $scope.items = [
             {'name':'School Item 1','address':'1920'},
             {'name':'Work Item 2','address':'4192'},
             {'name':'Ad Item 5','address':'2039'},
             {'name':'Cool Item 45','address':'2090'},
             {'name':'Cool Item 50','address':'1029'},
             {'name':'Cool Item 100','address':'1829'},
             {'name':'Cool Item 400','address':'1728'}
        ];
    }

HTML Code:

    <ul ng-controller="AppCtrl">
        <li ng-repeat="item in items|orderBy:['name','address']">
             {{item.name}} {{item.address}}
        </li>
    </ul>

Here is the fiddle http://jsfiddle.net/roverton/PuYLS/1/

Notice that when ordered the it will show 1 then 100, 45 then 400, 5 then 50 etc. I would like to order these alphanumerically. How would I do that in AngularJS?


Solution

  • One way to do this is to use a function to extract the number.

    function nameNumberSorter(item) {
        var numberPart = item.name.replace('NamedItem', '');
        return parseInt(numberPart);
    }
    

    And then alter your filter a bit:

    <div ng-app>
        <ul ng-controller="AppCtrl">
            <li ng-repeat="item in items|filter:deviceBindingFilter|orderBy:nameNumberSorter">
                {{item.name}} - {{item.address}}
            </li>
        </ul>
    </div>
    

    Alternatively, you could make an extra field on your model for sorting.

    function AppCtrl($scope) {
        $scope.items = [
             {'name':'NamedItem1','address':'1920', 'sortOrder': 1 },
             {'name':'NamedItem2','address':'4192', 'sortOrder': 2 },
             {'name':'NamedItem5','address':'2039', 'sortOrder': 5 },
             {'name':'NamedItem45','address':'2090', 'sortOrder': 45 },
             {'name':'NamedItem50','address':'1029', 'sortOrder': 50 },
             {'name':'NamedItem100','address':'1829', 'sortOrder': 100 },
             {'name':'NamedItem400','address':'1728', 'sortOrder': 400 }
        ];
    }
    

    And change your sort to look at this field.

    <div ng-app>
        <ul ng-controller="AppCtrl">
            <li ng-repeat="item in items|filter:deviceBindingFilter|orderBy:'sortOrder'">
                {{item.name}} - {{item.address}}
            </li>
        </ul>
    </div>