javascript - Generate random numbers in ng-repeat -
i'm trying create table random numbers filled in this:
<table> <tr> <td>123</td> <td>315</td> <td>356</td> <td>441</td> </tr> <tr> <td>664</td> <td>252</td> <td>236</td> <td>742</td> </tr> ... <!-- more rows above --> </table>
my html is:
<table> <tr ng-repeat="item in items"> <td>{{randnumgen()}}</td> <td>{{randnumgen()}}</td> <td>{{randnumgen()}}</td> </tr> </table>
my js is:
app.controller('tablectrl', function($scope) { $scope.items = [1,2,3,4,5,6,7,8,9,0]; $scope.randnumgen = function() { return math.floor((math.rand()*1000)+1); } });
it returns random number how want, throws js error saying:
"error: [$rootscope: infdig]"
and wont run scripts below controller.
the result of randomnumgen()
is, in angulars definition scoped variable. if detects change result of function trigger digest. result different in cases result in infinite digest loop.
you better off building array of random numbers before digest loop , assigning static non changing array scope , not causing undesired / unwanted digest loops occuring.
one approach build simplistic factory generate array when controller loaded. output contents.
angular.module('myapp', []) .factory('generator', function() { function buildrandarray(length) { var arr = []; for(var = 0; < (length || 10); i++) { var fill = []; (var j = 0; j < 3; j++) { fill.push(math.floor((math.random()*1000)+1)); } arr.push(fill); } return arr; } return { buildrandarray : buildrandarray } }) .controller('tablectrl', function($scope, generator) { $scope.items = generator.buildrandarray(10); });
now html be
<table> <tr ng-repeat="item in items"> <td ng-repeat="number in item"> {{number}} </td> </tr> </table>
Comments
Post a Comment