casso
casso

Reputation: 329

AngularJS - how to get unique values?

Could anyone please help me on getting unique values for Math.random()? I want to have random number in each 3x3 cell, but so far I'm manage to get only THIS result (same number in all 5 cells).

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>

Upvotes: 0

Views: 552

Answers (1)

Tom
Tom

Reputation: 7740

You're setting var Random on the global scope when your app initializes and then returning that instance every time. You need to get a new random number each time:

var app = angular.module("myApp", []);

app.controller("RandomCtrl", function ($scope){
    $scope.showRandom = function () {
        return Math.floor(Math.random() * 9 + 1);
    };
});

Or, if you do infact want Random on the global scope, make it the function, and then call it:

var app = angular.module("myApp", []);

app.controller("RandomCtrl", function ($scope){
    $scope.showRandom = Random;
});

var Random = function() {
    Math.floor(Math.random() * 9 + 1);
}

Upvotes: 2

Related Questions