Ronnie
Ronnie

Reputation: 11198

Angular ng-repeat with header views

I know the basic use of ng-repeat and I can generate a list easily.

<ul>
  <li ng-repeat="presentation in presentations">
    {{presentation.title}}
  </li>
</ul>

I have an array that is returned from PHP:

presentations = Array
(
    [0] => stdClass Object (
            [collection] => Collection A
            [title] => Title 1a
        )
    [1] => stdClass Object (
            [collection] => Collection A
            [title] => Title 2a
        )
    [2] => stdClass Object (
            [collection] => Collection B
            [title] => Title 1b
        )
    [3] => stdClass Object (
            [collection] => Collection B
            [title] => Title 2b
        )
    [4] => stdClass Object (
            [collection] => Collection C
            [title] => Title 1c
        )
    [5] => stdClass Object (
            [collection] => Collection C
            [title] => Title 2c
        )
    [6] => stdClass Object (
            [collection] => Collection C
            [title] => Title 3c
        )
)

You will notice that each object has a collection.

I need to basically create a header view per collection. I need it to display like below:

COLLECTION A
    - Title 1a
    - Title 2a
COLLECTION B
    - Title 1b
    - Title 2b
COLLECTION C
    - Title 1c
    - Title 2c
    - Title 3c

Only the titles would be clickable. Is this possible to do with just ng-repeat? I know I can sort each collection into separate arrays in PHP. Should I do that first? I'd like to just use ng-repeat if possible, I am just not sure how to approach this.

I plan on displaying this list in a nav-list as defined using twitter bootstrap.

nav-list

Upvotes: 1

Views: 1243

Answers (1)

lucuma
lucuma

Reputation: 18339

There are probably other way to achieve this with directives but

http://beta.plnkr.co/KjXZInfrDK9eRid2Rpqf

You define a function that you are going to call in order to show or hide the header:

// just a hard coded list of objects, we will output a header when the title changes
$scope.presentations = [{"title":"a", "other":"something else"},{"title":"a", "other":"something else"},{"title":"b", "other":"something else"},{"title":"b", "other":"something else"}, {"title":"b", "other":"something else"}]
$scope.currentTitle = '-1';
$scope.CreateHeader = function(title) {
      showHeader = (title!=$scope.currentTitle); 
       $scope.currentTitle = title;
      return showHeader;
}

Your html would look something like this:

<ul>
    <li ng-repeat="presentation in presentations">
      <div ng-show="CreateHeader(presentation.title)">
        {{presentation.title}} is the header
      </div>
      {{presentation.other}} is an attribute on the collection item
   </li>
</ul>

Upvotes: 2

Related Questions