Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ng-repeat index to display different html

I'm using Angular and ng-repeat as well as Semantic UI Grid layout.

I'm trying to display 5 columns in a row. When the fifth item is reached create a new row. The below creates a new row and column for each item in the data. I can see there is an index property with ng-repeat but not sure how to basically say if mod 5 == 0 output a new row element else just output a new column.

<div class="ui grid">
    <div class="row" ng-repeat="item in data.results">
        <div class="column">
            <div class="ui segment">
                {{item.original_title}}
            </div>
        </div>
    </div>
</div>

Thanks for the help

like image 825
Jon Avatar asked Jan 12 '23 21:01

Jon


1 Answers

The cleanest and most maintainable way would be in my opinion to write a directive. In your HTML you simply have:

<grid source="data.results" break="5" />

And in your JS you break your data into the correct structure within the controller and output it using the template:

    angular.module('yourApp', [])
    .directive('grid', function() {
      return {
          restrict: 'E',
          scope: {
            break: '=break',
            source: '=source'
          },
          controller: function($scope) {
            var total = Math.ceil($scope.source.length / $scope.break);
            $scope.data = new Array(total);
            for (var i = 0; i < total; ++i) {
              $scope.data[i] = $scope.source.slice(i * $scope.break, (i + 1) * $scope.break);
            }
          },
          template:
            '<div class="ui grid">' +
            '  <div class="row" ng-repeat="row in data">' +
            '    <div class="column" ng-repeat="item in row">' +
            '      <div class="ui segment">' +
            '        {{item.original_title}}' +
            '      </div>' +
            '    </div>' +
            '  </div>' +
            '</div>',
          replace: true
      };
  });
like image 143
dirkk Avatar answered Jan 22 '23 13:01

dirkk