有人可以帮助我获取Math.random()
的独特价值吗?我希望每个3x3单元格中都有随机数,但到目前为止,我只能获得THIS结果(所有5个单元格中的数字相同)。
的script.js:
var app = angular.module("myApp", []);
app.controller("RandomCtrl", function ($scope){
$scope.showRandom = function () {
return Random;
};
});
var Random = Math.floor(Math.random() * 9 + 1);
的index.html:
<div ng-app="myApp">
<div ng-controller="RandomCtrl">
<table>
<tr>
<td>{{showRandom()}}</td>
<td>{{showRandom()}}</td>
<td>{{showRandom()}}</td>
</tr>
<tr>
<td>{{showRandom()}}</td>
<td>{{showRandom()}}</td>
<td>{{showRandom()}}</td>
</tr>
<tr>
<td>{{showRandom()}}</td>
<td>{{showRandom()}}</td>
<td>{{showRandom()}}</td>
</tr>
</table>
</div>
答案 0 :(得分:2)
当您的应用初始化并且每次都返回该实例时,您在全局范围内设置var Random
。您需要每次都获得一个新的随机数:
var app = angular.module("myApp", []);
app.controller("RandomCtrl", function ($scope){
$scope.showRandom = function () {
return Math.floor(Math.random() * 9 + 1);
};
});
或者,如果您在全局范围内想要Random
,请将 it 作为该函数,然后调用它:
var app = angular.module("myApp", []);
app.controller("RandomCtrl", function ($scope){
$scope.showRandom = Random;
});
var Random = function() {
Math.floor(Math.random() * 9 + 1);
}