随机函数触发$摘要()错误 [英] Random function triggering $digest() error

查看:113
本文介绍了随机函数触发$摘要()错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作我的第一个角应用程序,并正在以下错误:


  

未捕获的错误:$ 10摘要()迭代到达。中止!


我想我已经分离出的来源,我使用随机()函数。这似乎是有道理的在我读到这个错误(方面的https:// github上。 COM /角/ angular.js /问题/ 705 )。但是,我不知道如何避免这个错误。

我已经重新错误这个简单的code:

randtest.js:

 函数FirstCtrl($范围){
      $ scope.randNum =功能(){
        变种的Rando = Math.floor(的Math.random()* 100);
        返回兰多;
      };
    }

index.html的

 <!DOCTYPE HTML>
< HTML NG-应用>
  < HEAD>
    &所述; SCRIPT SRC =htt​​ps://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js>&下; /脚本>
    &所述; SCRIPT SRC =randtest.js>&下; /脚本>
  < /头>
  <身体GT;
     < D​​IV NG控制器=FirstCtrl>
      &所述; H1> {{randNum()}}&下; / H1>
    < / DIV>
  < /身体GT;
< / HTML>


解决方案

不要直接设置$范围属性的功能。让scope属性引用的函数的结果:

  VAR R =功能(){
    变种的Rando = Math.floor(的Math.random()* 100);
    返回兰多;
  };
$ scope.randomNum = R();

HTML

 < H1> {{randomNum}}< / H1>

普拉克这里

更新 - NOT包装计算的功能似乎也避免了错误:

  $ scope.randomNum = Math.floor(的Math.random()* 100);

为什么会出现错误的原因是超越我...

I'm working on my first angular app and am getting the following error:

Uncaught Error: 10 $digest() iterations reached. Aborting!

I think I've isolated the source to my use of the random() function. This seems to make sense in terms of what I read about this error (https://github.com/angular/angular.js/issues/705). However, I don't know how to avoid this error.

I've recreated the error with this simple code:

randtest.js:

   function FirstCtrl($scope) {
      $scope.randNum= function(){
        var rando = Math.floor(Math.random()*100);
        return rando;
      };      
    }

index.html

<!doctype html>
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="randtest.js"></script>
  </head>
  <body>
     <div ng-controller="FirstCtrl">
      <h1>{{randNum()}}</h1>
    </div>
  </body>
</html>

解决方案

Don't set the $scope property directly to the function. Let the scope property reference the function's result:

var r = function(){
    var rando = Math.floor(Math.random()*100);
    return rando;
  }; 
$scope.randomNum =r();

HTML:

<h1>{{randomNum}}</h1>

Plunk here

Update - NOT wrapping the calculation in a function also seems to avoid the error:

$scope.randomNum = Math.floor(Math.random()*100);

The reasoning why the error occurs is beyond me...

这篇关于随机函数触发$摘要()错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆