Reputation: 1192
I am building an app using Angular. I have JSON that comes back from the server sorted by date. I bind to this data in the view.
A user may change what data is displayed in the view. This kicks off a request and the view gets updated as it is bound to the JSON data changes.
When Angular gets this JSON data it then sorts it alphabetically. I want to maintain the sort order that comes from the server.
I googled this a bit and found the following solution...
<div ng-repeat="key in notSorted(myData)" ng-init="data = myData[key]">
"notSorted" is a function on the controller...
$scope.notSorted = function(obj){
if (!obj) {
return [];
}
return Object.keys(obj);
}
This works fine initially. The data displays in the correct order. However it breaks the binding. So when the user tries to change the data being displayed, the view does not get updated as notSorted does not see the binding change.
I can think of a few hacky ways around this such as manually firing the updates but I would like to do this the correct angular way. Anyone know what that is?
Thanks
Upvotes: 1
Views: 312
Reputation: 1192
Because of the way the data was coming back from the server and how I needed to iterate over that data I wasn't able to get any of the "orderBy" or filter solutions to work. However I discovered that in Angular 1.4 they removed the default ordering (alphabetical/ascending) in favour of preserving the order the data was returned from the server...
http://jaxenter.com/angular-releases-1-3-update-1-4-beta-113906.html
I was using 1.3.x and simply updated to 1.4 and it worked OOTB.
Thanks
Upvotes: 0
Reputation: 2295
I believe you need this: https://docs.angularjs.org/api/ng/filter/orderBy
It works sort of like this:
<div ng-repeat="item in items | orderBy:'key'">
Upvotes: 2