我正在尝试使用 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));
}
});
最佳答案
您可以为按钮
周围的每个div
添加一个 Controller
,然后它们获得自己的范围
.
page.html
...
<div ng-repeat="die in dices" ng-controller="DieCtrl">
<button type="button" class="btn btn-default" ng-click="rollDice(1, die, 0, scope)">{{"d" + die}}</button>
<span>{{result}}</span>
</div>
...
controller.js
app.controller('DieCtrl', function ($scope) {
...
});
关于javascript - 使用 ng-repeat 提供多个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23816535/