【问题标题】:how to stop ng-repeat in the middle of the repeat in angular js如何在angular js中的重复中间停止ng-repeat
【发布时间】:2017-08-10 09:55:26
【问题描述】:

我正在尝试构建井字游戏,但在样式方面存在问题。我有一个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

【问题讨论】:

  • 我打开了 plunker 并向我展示了预期的 soduko 模型.. 有什么问题
  • 没关系,我打开了一个小窗口..

标签: javascript css angularjs angularjs-ng-repeat


【解决方案1】:

您需要以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>

【讨论】:

  • 嗨,很高兴我能帮上忙。它之所以有效,是因为 ng-repeat-end 指令需要以 ng-repeat-start 开头。普通的ng-repeat 没有被实现为比它在自己的元素中看得更远。因此ng-repeat-end 元素不在ng-repeat 中,它被添加到DOM 中一次。 square.id % 3 = NaNng-repeat 之外时,ng-if 中的 !NaN 为真,因此显示一次。看看各个 DOM 的不同之处就足够了。
  • 我明白了。所以如果你有 ng-repeat-start 你也必须有 ng-repeat-end。反之亦然?
【解决方案2】:

Angularjs 完全按照您的编码进行操作

第一个循环使用 square 类创建 9 个 div,然后第二个循环来制作分隔符

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多