如何在角度js的重复中间停止ng-repeat

时间:2017-03-18 23:51:48

标签: javascript css angularjs angularjs-ng-repeat

我正在尝试构建一个tic tac toe游戏,并且我遇到了样式问题。我有一个ng-repeat用于所有9个方格,并且需要在每第3个方格后添加一个div,以便可以构建下一行。我按照文档中的说明使用ng-repeat-end,但我不确定我做错了什么。

<p>Turn: <span ng-bind="vm.turn"></span></p>
<div class="container" ng-repeat="square in vm.squares track by square.id">
    <div class="square" ng-bind="square.piece" ng-click="vm.move(square.id)"></div>
</div>
<div ng-repeat-end class="row-divider" ng-if="!(square.id % 3)"></div>
<div>
<button class="btn btn-primary" click="newGame()">New game</button>

.square {
  border: 1px solid #000;
  width: 50px;
  height: 50px;
  float: left;
}

.row-divider {
  clear: both;
  display:block;
}


angular
.module('app')
.directive('ticTacToe', function(){
  return {
    restrict: 'E',
    templateUrl: 'tic-tac-toe.html',
    controller: TicTacToeController,
    controllerAs: 'vm'
  };

TicTacToeController.$inject = [];

function TicTacToeController(){
  var vm = this;
  vm.turn = 0;
  let currentPiece = 'X';
  vm.squares = [
    { id: 1, piece: null },
    { id: 2, piece: null },
    { id: 3, piece: null },
    { id: 4, piece: null },
    { id: 5, piece: null },
    { id: 6, piece: null },
    { id: 7, piece: null },
    { id: 8, piece: null },
    { id: 9, piece: null }
    ];
  vm.move = function(squareId) {
    console.log('click');
    let index = squareId - 1;
    currentPiece = vm.turn % 2 === 0 ? 'X' : 'O';
    vm.squares[index].piece = currentPiece;
    vm.turn++;
  };
  vm.newGame = function(){
    vm.turn = 0;
  }
};

})

以下是代码:https://plnkr.co/edit/XGhX5zVWCjSnn3OaKNQ6?p=preview

2 个答案:

答案 0 :(得分:2)

您需要从ng-repeat-start开始。

请参阅plunker https://plnkr.co/edit/jck226trFWnxGuWNuu02?p=preview

<p>Turn: <span ng-bind="vm.turn"></span></p>
<div class="container" ng-repeat-start="square in vm.squares track by square.id">
  <div class="square" ng-bind="square.piece" ng-click="vm.move(square.id)"></div>
</div>
<div ng-repeat-end class="row-divider" ng-if="!(square.id % 3)"></div>
<div>
  <button class="btn btn-primary" click="newGame()">New game</button>
</div>

答案 1 :(得分:0)

Angularjs正在完成您编码的内容

第一个循环用方形类创建9个div然后第二个循环来创建分隔符

尝试只制作一个包含2个div的循环,一个用于方块,另一个用于ng-if=!(square.id % 3)

的分隔符