AngularJS: How to write ascending sort filter

4.3k views Asked by At

I'm learning AngularJS and as an exercise trying to write an ascending sort filter:

This is my html file:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <script src="../Scripts/angular.min.js"></script>
  <script src="../Scripts/Controllers/app.js"></script> 
</head>
<body ng-app="myApp">
    <ul ng-init="names = ['Peter','Anton','John']">
       <li ng-repeat="name in names | sortAscending ">
           <span>{{name}}</span>
       </li>
   </ul>
</body>
</html>

This is my filter:

app.filter("sortAscending", function () {
    return function (input) {
        var result = [];
        for (var i = 0; i < input.length; i++) {
            if (input[i] > input[i + 1]) {
                result.push(input[i]);
            }
        }

        return result;
    }
});

I thing something is wrong in the loop regarding comparing the values.

What am I doing wrong?

2

There are 2 answers

0
Jeremy On BEST ANSWER

Three things:

  1. Your filter didn't return anything (missing return statement)

  2. The ng-init should only be used for aliases, it is not a good practice to declare variables in it. In your example, you should use the ng-init to apply your filter to your array, but the array itself should be declared in the controller.

  3. Your sorting algorithm is not working. To sort a simple array like that you can simply use the javascript sort() method.

Here is a working plunker with the three points corrected:

http://plnkr.co/edit/Qv9TDonFmpJsnIjx3dff?p=preview

 <ul  ng-init="sorted_names = (names | sortAscending)">
       <li ng-repeat="name in sorted_names ">
           <span>{{name}}</span>
      </li>
 </ul>

Edit: I guess you wanted to understand this as a form of exercise, so my solution addresses only the way you tried to solve the issue. Like other mentionned, it's true that you could use the orderby filter to make this easier in the end.

0
AGE On

How about orderBy:

<ul ng-init="names = [{name:'Peter'}, {name:'Anton'}, {name: 'John'}]">
    <li ng-repeat="name in names | orderBy:'+name' ">
        <span>{{name}}</span>
    </li>
</ul>

prefixing name with a + sign means ascending, alternatively - means descending.

Reference: orderBy

Edit: just as another answer suggests, please refrain from using ng-init for declaring variables/objects. as you can see in the AngularJS documentation a simple controller can be used, not only for most purposes but more importantly for exercise purposes.