Search code examples
angularjsangularjs-ng-repeatangularjs-orderby

angularjs ngRepeat orderBy when property key has spaces


I'm getting some data in JSON format which has spaces in the some of the keys:

[
    {
        "PlainKey": "SomeValue",
        "Spaced Key": "SomeValue"
    },
    {
        "PlainKey": "SomeValue2",
        "Spaced Key": "SomeValue2"
    }
]

This happens at some point:

$http.get('https://dl.dropboxusercontent.com/u/80497/htmlTesting/properties/credits.properties' + '?callback=JSON_CALLBACK').then(function (data) {
            $scope.credits = data.data;
        }, function (error) {
            $scope.errorOccured = true;
            console.log("Error:");
            console.log(error);
        });

and then ng-repeat is used to display it, with ordering:

<select ng-model="corder">
  <option value="PlainKey">Plain Key</option>
  <option value="Spaced Key">Spaced Key</option>
</select>

<li ng-repeat="credit in credits | orderBy:corder" >
.....
</li>

This doesn't work ( I get an exception ) (The PlainKey works because there are no spaces).

I also tried putting the values in ':

<select ng-model="corder">
  <option value="'PlainKey'">Plain Key</option>
  <option value="'Spaced Key'">Spaced Key</option>
</select>

This seems to change the order, but not correctly.

What Am I missing?

Thanks!


Solution

  • Comments appeared to help so I'm including it as an answer:

    One way to sort items with spaces in their object property names is to pass a predicate sort function into orderBy instead of specifying the object property name. The relevant modifications in particular:

    HTML:

    <li ng-repeat="credit in credits | orderBy:predicate">
    

    JS:

    $scope.predicate = function(val) {
      // $scope.corder corresponds to the object property name to sort by
      return val[$scope.corder];
    }
    

    Demonstration Plunker.