0

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>
2
  • 1
    Use $scope.showRandom = function () { return Math.floor(Math.random() * 9 + 1); }; instead. Commented May 14, 2014 at 14:49
  • You may want to look into directives with isolated scope - docs.angularjs.org/guide/directive Commented May 14, 2014 at 14:58

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.