Search code examples
angularjsangularjs-filter

Custom orderBy in AngularJS without absolute string comparison?


I'm building a small CSS beautifier for my system, which will only build when the CSS is in a particular order. The idea is to dump CSS into a textarea, and for the app to generate an ordered version of the code. I managed to do it, but only if the code pasted in the textarea has no properties.

For example:

content
margin
font-size

Will work.

But if it's proper code with properties:

content: 'test';
margin: 10px;
font-size: 1em;

Then it won't.

I think that what is failing is that the comparative function will only consider the string as a full, not as a partial.

Here's the comparative function and a JS Bin.

$scope.customOrder = function (item) {
  switch (item) {
    case 'display':
        return 1;
    case 'flex':
        return 2;
    case 'flex-basis':
        return 3;
    case 'flex-direction':
        return 4;
    ... 
  }
};

Any ideas on how to address this?


Solution

  • Before the switch, parse the attribute name, like so:

    $scope.customOrder = function (item) {
       var parsedItem = item.substr(0, item.indexOf(':'));
       switch (parsedItem) {
         case 'display':
           return 1;
          case 'flex':
            return 2;
          ...