angular.js ng-repeat for creating grid

后端 未结 11 2021
终归单人心
终归单人心 2020-11-30 03:22

I\'m trying to create a grid using bootstrap 3 and angularjs.

The grid I\'m trying to create is this, repeated using ng-repeat.

11条回答
  •  时光取名叫无心
    2020-11-30 03:47

    The accepted answer is the obvious solution however presentation logic should remain in view and not in controllers or models. Also I wasn't able to get the OP's solution to work.

    Here are two ways to do create grid system when you have a flat list(array) of items. Say our item list is a alphabet:

    Plunker here

    $scope.alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
                       'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    

    Method 1:

    This is a pure angular solution.

    Letter {{i + 1}} is: {{alphabet[i]}}

    The outer loop execute after every 4 iterations and creates a row. For each run of the outer loop the inner loop iterates 4 times and creates columns. Since the inner loop runs 4 times regardless of whether we have elements in array or not, the ng-if makes sure that no extraneous cols are created if the array ends before inner loop completes.

    Method 2:

    This is much simpler solution but requires angular-filter library.

    Letter {{$index + 1}} is: {{letter}}

    The outer loop creates groups of 4 letters, corresponding to our 'row'

    [['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ... ]
    

    The inner loop iterates over the group and creates columns.

    Note: Method 2 might require evaluation of filter for each iteration of outer loop, hence method 2 may not scale very well for huge data sets.

提交回复
热议问题