Javascript AngularJS-如何获得唯一值?
有人能帮我获取Javascript AngularJS-如何获得唯一值?,javascript,angularjs,Javascript,Angularjs,有人能帮我获取Math.random()的唯一值吗?我希望在每个3x3单元格中都有随机数,但到目前为止,我只能得到一个结果(所有5个单元格中的数字相同) script.js: var app = angular.module("myApp", []); app.controller("RandomCtrl", function ($scope){ $scope.showRandom = function () { return Random; }; });
Math.random()
的唯一值吗?我希望在每个3x3单元格中都有随机数,但到目前为止,我只能得到一个结果(所有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);
<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>
index.html:
var app = angular.module("myApp", []);
app.controller("RandomCtrl", function ($scope){
$scope.showRandom = function () {
return Random;
};
});
var Random = Math.floor(Math.random() * 9 + 1);
<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>
{{showRandom()}}
{{showRandom()}}
{{showRandom()}}
{{showRandom()}}
{{showRandom()}}
{{showRandom()}}
{{showRandom()}}
{{showRandom()}}
{{showRandom()}}
当应用程序初始化时,您正在全局范围上设置var Random
,然后每次都返回该实例。每次都需要获得一个新的随机数:
var app = angular.module("myApp", []);
app.controller("RandomCtrl", function ($scope){
$scope.showRandom = function () {
return Math.floor(Math.random() * 9 + 1);
};
});
或者,如果您确实希望在全局作用域上使用Random
,请将其设为函数,然后调用它:
var app = angular.module("myApp", []);
app.controller("RandomCtrl", function ($scope){
$scope.showRandom = Random;
});
var Random = function() {
Math.floor(Math.random() * 9 + 1);
}
使用
$scope.showRandom=function(){return Math.floor(Math.random()*9+1);}相反,您可能希望查看具有独立作用域的指令-