Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 662
Ben Avatar asked Apr 17 '14 13:04

Ben


2 Answers

Simplest way, just surround a field name with UTF8 code for quotation mark:

HTML

<li ng-repeat="item in items | orderBy:'\u0022Spaced Key\u0022'">

JS

$scope.orderKey = '\u0022Spaced Key\u0022';
like image 50
Alex Avatar answered Sep 21 '22 12:09

Alex


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.

like image 43
miqh Avatar answered Sep 18 '22 12:09

miqh