我正在尝试使用ng-repeat创建一个按钮列表,每个按钮都可以单击以执行相同的功能,在这种情况下,滚动模具。我如何得到它,以便每个按钮都有自己独特的结果参考?当前单击一个按钮时,将完成正确的计算,但结果显示在每个按钮旁边,而不仅仅是单击的按钮。
这是我到目前为止(fiddle):
in 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));
}
});
答案 0 :(得分:1)
您可以为controller
周围的每个divs
添加button
,然后他们会获得自己的scope
。
<强> 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) {
...
});
答案 1 :(得分:0)
ng-repeat
为每次迭代创建一个新的子范围,但$scope
方法中的rollDice
变量是父范围。最简单的方法是从rollDice返回结果,而不是直接设置范围属性,并在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;
}
另一种方法是让您的子作用域上的对象保存结果并将该对象传递给您的单击函数。您可以使用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;
}