AngularJS -如何获得唯一值

AngularJS - how to get unique values?

本文关键字:唯一 何获得 AngularJS      更新时间:2023-09-26

谁能帮我获得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);

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>

当你的应用程序初始化时,你在全局作用域上设置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);
}