2

To be able to fix a sorting issue i need to change the compare-method of the angular library. So far i just changed the angular.js codefile directly but when we update to a newer version it will be lost. I read that it's possible to override methods in javascript.

I tried something like but it did not do the job:

angular.orderByFilter.compare = function (v2, v2) {
    //Code goes here
}

Any ideas how to overwrite that function? This is how the function is declared inside the angularjs file:

function orderByFilter($parse) {
  return function(array, sortPredicate, reverseOrder) {

    function compare(v1, v2) {
      var t1 = typeof v1;
      var t2 = typeof v2;
      if (t1 === t2 && t1 === "object") {
        v1 = objectToString(v1);
        v2 = objectToString(v2);
      }
      if (t1 === t2) {
        if (t1 === "string") {
           v1 = v1.toLowerCase();
           v2 = v2.toLowerCase();
        }
        if (v1 === v2) return 0;
        return v1 < v2 ? -1 : 1;
      } else {
        return t1 < t2 ? -1 : 1;
      }
    }
  };
}
MS Dev
  • 29
  • 2
  • Don't override it. Create your own filter. Some examples - [Scotch.io](https://scotch.io/tutorials/building-custom-angularjs-filters), [Official Tutorial](https://docs.angularjs.org/tutorial/step_09) – callmekatootie Jul 01 '15 at 17:22

1 Answers1

0

There are many solutions that do not include overriding default angular method. You can use filters, JS sort, JQuery sort, even write your own sort function.

Have you looked into the very basic JavaScript .sort()?

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.sort(function(item1, item2) {
    return item1 > item2; //Do whatever you need here
});

If you need it in some special case such as in ng-repeat take a look at Custom sort function in ng-repeat

Update

Ok, if you really, really, REALLY need to override the default filter, I figured out how to do it.

I still emphasize that there are far better ways to achieve what you want using your own filters.

In either case, this is how you can override the fault orderBy filter:

// You can use the filter using the normal orderBy syntax, e.g.:
// <div ng-repeat="item in items | orderBy : 'name' : reverse"> </div>

myApp.filter('orderBy', function() { // myApp is your angular app (duh..)
   return function(array, sortPredicate, reverseOrder) {
       if (array != undefined) { // order any way you like here
           return _.sortBy(array, sortPredicate);
       }
   }
});

Hope this helps =)

Community
  • 1
  • 1
SDekov
  • 9,276
  • 1
  • 20
  • 50
  • Thanks Stoyan for showing another way. However, as i'd like to keep the regular ng-repeat orderBy syntax (the one with string) and the original compare method doesn't behave well with umlauts i really would like to override it. – MS Dev Jul 02 '15 at 07:45
  • Please look at the update and let me know if you have any questions. – SDekov Jul 02 '15 at 09:46