简体   繁体   中英

Angular.js: Add tag every three elements

I have a list of divs and I want to achieve the following html example:

<div class="groups">
  <div class="group">Whatever 1</div>
  <div class="group">Whatever 2</div>
  <div class="group">Whatever 3</div>
</div>
<div class="groups">
  <div class="group">Whatever 4</div>
  <div class="group">Whatever 5</div>
  <div class="group">Whatever 6</div>
</div>

I have the following:

<div class="group" ng_repeat="group in groups">
    <div>{{group.name}}</div>
</div>

How can I encapsulate "group" divs inside a "groups" for every three elements? Also I want to add elements dynamically and have the same behavior.

EDIT: using a filter will not work do to infinite loop. Here is a solution with the filtering logic in the controller's watch function. It could be refactored and placed inside a service. But for the sake of simplicity it is not done here.

Here is a working Plunker: http://plnkr.co/edit/tINqbztypUqv674hvDbo

I would go with the solution proposed by @Mik378 augmented and manipulate data initially in your controller:

<div ng-controller="yourCtrl">

    <div class="groups" ng-repeat="groups in groupedArray">
        <div class="group" ng-repeat="group in groups">
            <div>{{group.name}}</div>
        </div>
    </div>
</div>

The controller:

angular.module('yourApp')
    .controller('yourCtrl', function ($scope) {
        $scope.tobeGroupedArray = [
            {name: 'group1'},
            {name: 'group2'},
            {name: 'group3'},
            {name: 'group4'},
            {name: 'group5'},
            {name: 'group6'},
            {name: 'group7'},
            {name: 'group8'},
            {name: 'group9'}
        ];

        $scope.$watch(
            'tobeGroupedArray',
            function (newVal) {
                if (!newVal) {
                    return;
                }
                $scope.groupedArray = [];
                newVal.forEach(function (group, idx) {
                    if (idx % 3 === 0) {
                        $scope.groupedArray.push([]);
                    }
                    $scope.groupedArray[$scope.groupedArray.length - 1].push(group);
                });
            },
            true
        );
    });

I presume you would have an array of groups, and each "groups" being an array. Why not the following:

<div class="groups" ng-repeat="groups in groupsArray">
  <div class="group" ng-repeat="group in groups">
      <div>{{group.name}}</div>
  </div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM