Sorting Ordered List element in AngularJS

Last Reply 27 days ago By dharmendr

Posted 27 days ago

How to Sort ordered list in asc or desc in angularjs

You are viewing reply posted by: dharmendr 27 days ago.
Posted 27 days ago

Hi rani,

You can use JavaScript Array sort and reverse method.

Check this example.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope) {
            $scope.Fruits = ['Mango', 'Apple', 'Banana', 'Orange', 'Guava'];
            $scope.SortFruits = function (order) {
                if (order == 'asc') {
                    $scope.Fruits.sort();
                } else if (order == 'desc') {
                    $scope.Fruits.sort();
                    $scope.Fruits.reverse();
                }
            }
        });
    </script>
</head>
<body>
    <div ng-app="MyApp" ng-controller="MyController">
        <input type="button" value="Ascending Fruits" ng-click="SortFruits('asc')" />
        <input type="button" value="Descending Fruits" ng-click="SortFruits('desc')" /><br />
        <ol><li ng-repeat="fruit in Fruits">{{fruit}}</li></ol>
    </div>
</body>
</html>

Demo