Last active
          December 23, 2015 10:49 
        
      - 
      
- 
        Save justinklemm/6624575 to your computer and use it in GitHub Desktop. 
    AngularJS Filter for Ordering Objects (Associative Arrays or Hashes) with ngRepeat
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | <ul> | |
| <li ng-repeat="item in items | orderObjectBy:'color':true">{{ item.color }}</li> | |
| </ul> | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | var app = angular.module('sample'); | |
| // inside your controller | |
| $scope.items = {}; | |
| $scope.items['color-1'] = {color: "red"}; | |
| $scope.items['color-2'] = {color: "green"}; | |
| $scope.items['color-3'] = {color: "blue"}; | |
| // define filter on app | |
| app.filter('orderObjectBy', function() { | |
| return function(items, field, reverse) { | |
| var filtered = []; | |
| angular.forEach(items, function(item) { | |
| filtered.push(item); | |
| }); | |
| filtered.sort(function (a, b) { | |
| if(a[field] > b[field]) return 1; | |
| if(a[field] < b[field]) return -1; | |
| return 0; | |
| }); | |
| if(reverse) filtered.reverse(); | |
| return filtered; | |
| }; | |
| }); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment