Search code examples
angularjstwitter-bootstrapangularjs-filterangularjs-orderby

Sorting elements in AngularJS for nested ng-repeat


I am using bootstrap to display a grid of projects with each row having 3 columns. In order to accomplish this, I am using ng-repeat twice like below.

<div class="row" ng-repeat="chunk in projects">
  <div class="col-sm-4" ng-repeat="project in chunk | orderBy:'title'">
    {{project.title}}
  </div>
</div>    

I want to be able to sort the project based on its title field. Applying a filter only sorts a subset of the whole list i.e. sorts at the chunk level rather than the projects level.

var projects = [[{"title":"Z"},{"title":"A"},{"title":"M"}],
  [{"title":"Z"},{"title":"A"},{"title":"M"}]];

After the orderBy happens, the rows are A M Z, A M Z. How do I get it to display A A M, M Z Z?

Here is the plunk for the above problem. //EDIT : The above plunk points to the solution because I updated the plunk.


Solution

  • I was able to solve this problem finally through filter chaining. I used angular-filter module/library but this can be even done without angular-filter.

    <div class="container" ng-controller="ExampleController as exampleVm">
    <div class="row" ng-repeat="chunk in exampleVm.projects|  chunkBy: 'title' | groupBy : 3">
      <div class="col-sm-4" ng-repeat="project in chunk">
        {{project.title}}
      </div>
    </div>
    

    I flattened the array and made it look like this.

    var projects = [{"title:Z"},{"title":"A"},{"title":"M"},{"title:Z"},{"title":"A"},{"title":"M"}]
    

    In the filter chain, I order the elements in the flattened array first by title and then divide it into subarrays of 3 elements each. Hope this helps.

    You can find the plunk here.