我正在尝试创建一个带有ng-repeat的按钮的列表,每个按钮都可以单击以执行相同的功能,在这种情况下,请滚动模具。我如何获得它,以便每个按钮对结果都有自己的唯一引用?当前,当单击一个按钮时,将进行正确的计算,但结果显示在每个按钮旁边,而不仅仅是单击的按钮。

这是我到目前为止的(fiddle)内容:

在HTML

...
<div ng-repeat="die in dice">
    <button type="button" class="btn btn-default" ng-click="rollDice(1, die, 0, scope)">{{"d" + die}}</button>
    <span>{{result}}</span>
</div>
...


在controller.js中

angular.module('diceAngularApp')
.controller('DiceController', function ($scope) {

$scope.dice = [2,3,4,6,8,10,12,20,100];
$scope.result = 0;

$scope.rollDice = function(numRolls, numSides, bonus) {
  var total = "";
  var rolls = new Array( numRolls );

  for (var i = 0; i < numRolls; i++ ) {
    var roll = randomInt( 1, numSides );
    rolls[i] = roll;
    total += roll;
  }

  $scope.result = total;
}

    function randomInt( intMin, intMax ) {
        intMax = Math.round( intMax );
        intMin = Math.round( intMin );
        return intMin + Math.floor( intMax * (Math.random() % 1));
    }

});

最佳答案

ng-repeat为每次迭代创建一个新的子范围,但是$scope方法中的rollDice变量是父范围。最简单的方法是从rollDice返回结果,而不是直接设置scope属性,然后在ng-click (fiddle)中设置该值:

ng-click="result = rollDice(1, die, 0)"


另一种方法是通过传递$event变量并使用angular.element($ event.target).scope()来访问子作用域:(fiddle)

<div ng-repeat="die in dice">
    <button type="button"
        class="btn btn-default"
        ng-click="rollDice(1, die, 0, $event)"> <!-- pass $event -->
            {{"d" + die}}<br/>
    </button>
    <span>{{result}}</span>
</div>


Javascript:

$scope.rollDice = function(numRolls, numSides, bonus, $event) {
  var total = "";
  var rolls = new Array( numRolls );

  for (var i = 0; i < numRolls; i++ ) {
    var roll = randomInt( 1, numSides );
    rolls[i] = roll;
    total += roll;
  }

  // get scope for element sending event and use it
  angular.element($event.target).scope().result = total;
}


还有一种方法是在子范围内有一个对象来保存结果并将该对象传递给您的click函数。您可以使用ng-init (fiddle)初始化对象

<div ng-repeat="die in dice">
    <button
        ng-init="results = { result: 0 }"
        type="button"
        class="btn btn-default"
        ng-click="rollDice(1, die, 0, results)">
            {{"d" + die}}<br/>
    </button>
    <span>{{results.result}}</span>
</div>


Javascript:

$scope.rollDice = function(numRolls, numSides, bonus, results) {
  var total = "";
  var rolls = new Array( numRolls );

  for (var i = 0; i < numRolls; i++ ) {
    var roll = randomInt( 1, numSides );
    rolls[i] = roll;
    total += roll;
  }

  results.result = total;
}

10-05 20:51
查看更多