javascript - How to prevent "Error: $rootScope:infdig" when different value each time is intended behavior -
i'm working on page using angularjs(with aria, animate, material, messages, sanitize , route), everyting working fine have bit of problem. angular likes throw "error: $rootscope:infdig" when value returned function different every time page refreshed 1 function wrote meant do.
the code:
<script> angular.module('tht', ['ngmaterial', 'ngsanitize', 'ngmessages', 'nganimate', 'ngaria']) .controller('maincontroller', ['$scope', '$rootscope', function($scope, $rootscope) { $rootscope.version = '0.1'; $rootscope.name = 'tht'; $rootscope.author = 'd3add3d'; $rootscope.year = '2016'; $scope.jokes = ["we ate bunch of doritos , page blank...", "sometimes looks this...", "kappa, kappa, kappa, kappa...", "this text changes every time refresh page, weird huh o_o", "we out of doritos :-/", "powered satisfaction... wait", "instead of working on page, i'm writing these jokes #procrastination", "have hug or 2 *hugs*", "<3", "<3~~~", "this joke simple... return array[math.floor(math.random() * array.length)];", "go eat chocolate, helps ;)", "i love :-* <3", "[~~hug~~]", "[?bug?]"]; $scope.randomjoke = function() { return $scope.jokes[math.floor(math.random() * $scope.jokes.length)]; //function returns different value (almost) every time called } }]); </script>
the html:
<div ng-controller="maincontroller" ng-hide> <header>hello, <b>{{name}}</b>, version <b>{{version}}</b> <article><br>{{randomjoke()}}</article> <!-- causes error --> </header> <footer>© <b>{{author}}</b>, {{year}}</footer> </div>
so question is: there way avoid error in case want value different every time?
this won't work, because of how interpolation bindings {{ }}
evaluated.
interpolation bindings not evaluated once per page reload. evaluated every $digest
cycle, determine if value needs updated, cornerstone of how angular 2 way binding works. unfortunately, functions executed inside interpolation binding cause $digest
cycle fire, in order determine if function call has made changes requiring other bindings updated.
in case, creates bit of issue, since $digest
never stable. every call $digest
generates new randomjoke
, causes $digest
fire again. if review infdig
error, can see watchers fired in last 5 iterations
showing 5 different jokes in oldval
, newval
.
the infdig
error failsafe, angular stops digest after 10 iterations, ensure don't lock browser completely. in practice, could use code way, application suffer poor performance result.
the better method bind variable assigned result of function call, evaluated once, during controller initialization.
Comments
Post a Comment