title: AngularJS Group By Directive without External Dependencies
body: <p>I'm new to Angular and would like to learn the best way to handle a problem. My goal is to have a reusable means to create group by headers.  I created a solution which works, but I think this should be a directive instead of a scope function within my controller, but I'm not sure how to accomplish this, or if a directive is even the right way to go.  Any inputs would be greatly appreciated.</p>
  
  <p>See my current approach working on <a href="http://jsfiddle.net/drubarth/Nedfw/14/" rel="noreferrer">jsFiddle</a></p>
  
  <p>In the HTML it's a simple list using ng-repeat where I call my newGrouping() function on ng-show.  The function passes a reference to the full list, the field I want to group by, and the current index.</p>
  
  <pre><code>&lt;div ng-app&gt;
  &lt;div ng-controller='TestGroupingCtlr'&gt;
      &lt;div ng-repeat='item in MyList'&gt;
          &lt;div ng-show="newGrouping($parent.MyList, 'GroupByFieldName', $index);"&gt;
              &lt;h2&gt;{{item.GroupByFieldName}}&lt;/h2&gt;
          &lt;/div&gt;
          {{item.whatever}}
      &lt;/div&gt;
  &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>In my controller I have my newGrouping() function which simply compares the current to the previous, except on the first item, and returns true or false depending upon a match. </p>
  
  <pre><code>function TestGroupingCtlr($scope) {
  
    $scope.MyList = [
      {GroupByFieldName:'Group 1', whatever:'abc'},
      {GroupByFieldName:'Group 1', whatever:'def'},
      {GroupByFieldName:'Group 2', whatever:'ghi'},
      {GroupByFieldName:'Group 2', whatever:'jkl'},
      {GroupByFieldName:'Group 2', whatever:'mno'}
    ];
  
    $scope.newGrouping = function(group_list, group_by, index) {
    if (index &gt; 0) {
      prev = index - 1;
      if (group_list[prev][group_by] !== group_list[index][group_by]) {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
    };
  }
  </code></pre>
  
  <p>The output will look like this.</p>
  
  <p><strong>Group 1</strong></p>
  
  <ul>
  <li>abc</li>
  <li>def</li>
  </ul>
  
  <p><strong>Group 2</strong></p>
  
  <ul>
  <li>ghi</li>
  <li>jkl</li>
  <li>mno </li>
  </ul>
  
  <p>It feels like there should be a better way.  I want this to be a common utility function that I can reuse.  Should this be a directive?  Is there a better way to reference the previous item in the list than my method of passing the full list and the current index? How would I approach a directive for this?</p>
  
  <p>Any advice is greatly appreciated.</p>
  
  <p>UPDATE: Looking for an answer that does not require external dependencies.
  There are good solutions using underscore/lodash or the angular-filter module.</p>
  
  <p>Darryl</p>