i have seen many posts on this but for some reason I continue to run into a problem. I am returning multiple promises with $q.all. Each returned promise (from different vendors) is returning identically formatted arrays of objects. After everything is returned and everything is then processed into a single array of objects and then I need to sort the array of objects based on one of three SORT values : (vendor, price, price_estimate)
But when its returned to my controller nothing is sorted.
Sample Object: { "vendor" : "Aaa Company", "product" : "This prod", "description" : "this cool prod", "price" : 27.50, "price_estimate" : 23.25, "category" : "tool", ... } .factory('Products', function($http,$q,promise1,promise2,promise3,promise4,promise5) { var prods = [] ; function sortProds(key) { prods.sort(function(a,b) { if (key == "vendor") { return ((x<y) ? -1 : ((x > y) ? 1: 0)) ; } else { return parseFloat(a.key) - parseFloat(b.key) ; } }) ; } function getProds() { prods = [] ; $q.all([promise1(),promise2(),promise3(),promise4(),promise5()]).then(function(response){ var z=0 ; // process all results, ie: [0][{a:1,b:2,c:3},{a:4,b:5,c:6}], [1]:[{a:7,b:8,c:9} for (var y=0;y<response.length;y++) { // process individual result,ie: [{a:1,b:2,c:3},{a:4,b:5,c:6}] for (var x=0;x<response[y].length;x++) { response[y][x].prodID = z++ ; // reset prodID prods.push(response[y][x]) ; } } // sort option could be 'vendor','price','price_estimate' prodInfo.sortBy = getDB("prod_sortOption") ; sortProds(prodInfo.sortBy) ; }); } return { all: function() { return [prods,prodInfo.sortBy] ; } } })
Because I can't get the above to work, I then tried auto-sorting the returned results in the controller, but it too is not working. In my controller:
$scope.doSort = function(key,prodList) { prodList.sort(function(a,b) { var x = a[key]; var y = b[key] ; if (key == "vendor") { return ((x<y) ? -1 : ((x > y) ? 1: 0)) ; } else { return parseFloat(a.key) - parseFloat(b.key) ; } }) ; return prodList ; } var returnedProds = Products.all() ; $scope.prods = $scope.doSort(prodInfo.sortBy,returnedProds[0]) ; // $scope.prods is what is used to in my template to populate the web view.
HOWEVER, if the user in the webview does a manual sort on a button click that has ng-click="doSort('price',prods)"
it works as intended...buts its the same doSort
that isn't working on the auto-sorted returned results.
I hope all this makes sense. I can't figure out why its not sorting in the service...or again during the auto-sort upon returned results....but then does work when manually done. Ugh!