0

Below is the sort criteria from A to Z: 1) special characters 2) numbers 3) alphabet

For example:-

$scope.cards = ["815 BRAZOS ST AUSTIN TX 78701","7745 CHEVY CHASE DR AUSTIN TX 78752","701 BRAZOS ST AUSTIN TX 78701","555 ROUND ROCK WEST DR ROUND ROCK TX 78681","400 W 15TH ST AUSTIN TX 78701"]

Expected result after sorting:-

400 W 15TH ST AUSTIN TX 78701
555 ROUND ROCK WEST DR ROUND ROCK TX 78681
701 BRAZOS ST AUSTIN TX 78701
815 BRAZOS ST AUSTIN TX 78701
7745 CHEVY CHASE DR AUSTIN TX 78752

I want to achieve this using Angular orderBy filter. As in JS custom sort function, we got two arguments and by manipulating that we can return >0, <0 and 0 to achieve custom sort.

My Attempt

<div ng-controller="MyCtrl">
  <ul ng-repeat="card in cards | orderBy:myValueFunction">
      <li>{{card}}</li>
    </ul>
</div>

JS

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.cards = ["815 BRAZOS ST AUSTIN TX 78701","7745 CHEVY CHASE DR AUSTIN TX 78752","701 BRAZOS ST AUSTIN TX 78701","555 ROUND ROCK WEST DR ROUND ROCK TX 78681","400 W 15TH ST AUSTIN TX 78701"]

    $scope.myValueFunction = function(card,card1) {
        console.log(card);
        console.log(card1);
        return card;
    } 
}

JSfiddle link

Thanks

1 Answer 1

4

According to documentation your function should return a value, that would be used for sorting using standard comparison operators (<,>,=).

So in your case your function should return an value, that would determine sorting. For your case, you need to put some advanced logic to produce such value.

For simples example (sort by first numbers), you get:

$scope.myValueFunction = function(card) {
        return card.split(' ')[0]|0;
}

At least you'll have what you've requested in your small sample, see here: http://jsfiddle.net/zjvsu/529/

UPDATED

If you want to compare two values just like standard javascript sort custom function then you will have to use your own filter which returns sorted array.

Sign up to request clarification or add additional context in comments.

3 Comments

But how can I compare? As in standard javascript sort, we got two arguments for comparison but in angular we are getting only current value. please see updated fiddle jsfiddle.net/zjvsu/534
using standard orderBy filter you can't. But you can create your own filter that will produce sorted array.
Thanks, please edit your answer somehow so that I can remove my minus vote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.