javascript - Get random number in ng-repeat angular -
i need random number in cycle angular. tried in template:
<div ng-app="app" ng-controller="base" > <div ng-repeat="item in items"> <img ng-src="/img/img{{getrandomimg()}}.png"> </div> </div>
and function in base controller:
$scope.getrandomimg = function(){ return math.floor((math.random()*3)+1); }
when page loaded have error: $rootscope:infdig infinite $digest loop
i tried directive
app.directive('randomimage', [ function() { return { restrict: 'a', link: function($scope, element, attrs) { var rand = math.floor((math.random()*3)+1); $(element).attr('src', '/img/tracks/trackimg'+rand+'.png'); } } } ]);
and in template:
<div ng-app="app" ng-controller="base" ng-repeat="item in items"> <img data-random-image=""> </div>
it works correctly. when update items
in controller not re-generated images, remain same. why?
this angular documentation:
"this error occurs when application's model becomes unstable , each $digest cycle triggers state change , subsequent $digest cycle. angular detects situation , prevents infinite loop causing browser become unresponsive.
for example, situation can occur setting watch on path , subsequently updating same path when value changes."
<div ng-repeat="user in getusers()">{{ user.name }}</div> ... $scope.getusers = function() { return [ { name: 'hank' }, { name: 'francisco' } ]; };
the problem in "items" array. read this: https://docs.angularjs.org/error/$rootscope/infdig
Comments
Post a Comment