Search code examples
angularjsangularjs-scopeangularjs-orderby

Get order of variables in scope after dynamic OrderBy


I currently have:

ng-repeat="pesron in people | orderBy:variable"

As events occur, the variables changes and thus the order of the persons changes as well.
Question: How do I access the people in the controller as an array, ordered appropriately?

I tried:

angular.forEach($rootScope.people, function(value,index) {  
    console.log(value);  
});

However, this only gives the variables in the order that they are added to the scope.


Solution

  • Inject $filter into your controller, and do the following

    var orderedPeople = $filter('orderBy')($scope.people, 'variable')
    

    If you want this to change whenever variable changes, then you'd need to put the assignment in a $scope.$watch.

    However, the bigger picture is that you probably shouldn't structure your app this way. Namely, you're

    1. Filtering your array on every digest cycle, even though variable only changes once in a while.
    2. Filtering it in your view and then repeating that work in the controller.

    The following would be more efficient:

    In your controller:

    people = []; // initialize me
    $scope.$watch(function() { return people; }, sortList, true); 
    // we're resorting whenever any property on $scope.people changes.
    // This isn't the best solution if people is a huge and complex object
    function sortList() {
      $scope.orderedPeople = $filter('orderBy')(people, 'variable');
    }
    
    // somewhere else
    doSomethingWith($scope.orderedPeople);
    

    In your view:

    <div ng-repeat="person in orderedPeople"></div>
    

    See https://docs.angularjs.org/api/ng/filter/orderBy and https://docs.angularjs.org/api/ng/filter/filter