Angularjs ngRepeat orderBy when property key has spaces

I get some data in JSON format that have spaces in 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 used to display it in order:

 <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 does not work (I get an exception) ( 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 is similar to reordering, but not correct.

What am I missing?

Thanks!

+7
angularjs angularjs-ng-repeat angularjs-orderby
source share
2 answers

The comments turned out to be useful, so I include them as an answer:

One way to sort items with spaces in object object names is to pass the predicate sort function to orderBy instead of specifying the object property name. Relevant changes, 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 of Plunker .

+7
source share

The easiest way: just enter the name of the field with the UTF8 code for the quote:

HTML

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

Js

 $scope.orderKey = '\u0022Spaced Key\u0022'; 
+10
source share

All Articles