多次执行角度作用域函数 [英] Angular scope function executed multiple times

查看:24
本文介绍了多次执行角度作用域函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在作用域上定义了一个函数.当我从 {{}} 内的视图调用它时,它执行 X 次.

控制器

function testCtrl($scope) {$scope.myFunc = 函数(名称){返回你好"+姓名;}}

HTML

{{myFunc('Joe')}}

你可以在这个例子中看到它:http://jsfiddle.net/rbRvD/2/

或使用 Plunker:http://plnkr.co/edit/LLQ7cKs2fEoBwv0C5XPE

我猜这是做错了,但为什么执行了这么多次?

解决方案

你的函数运行了 10 次.为什么是10?为什么不是 100?

答案在文档中:

<块引用>

watch 监听器可能会改变模型,这可能会触发其他听众开火.这是通过重新运行观察者直到没有检测到变化.重新运行迭代限制为 10 以防止无限循环死锁.

当您看到这种情况发生时,这意味着您正在以这样一种方式更改模型,即 Angular 必须重新运行摘要并再次启动手表.在您的特定情况下,您正在调用一个更新计数器的函数,该计数器显示在页面上.当计数器值改变时,它会再次运行摘要,调用更新计数器等的函数.

Angular 期望您(并且确实鼓励您)更改模型并让视图响应这些更改,而不是相反.

I have defined a function on scope. And when I call it from the view inside {{}} it executes X number of times.

Controller

function testCtrl($scope) {
   $scope.myFunc = function(name) {
       return "Hello " + name;
   }
}

HTML

<div>{{myFunc('Joe')}}</div>

You can see it in this example: http://jsfiddle.net/rbRvD/2/

Or with Plunker: http://plnkr.co/edit/LLQ7cKs2fEoBwv0C5XPE

I guess this is done the wrong way, but why is it executed so many times?

解决方案

Your function is run 10 times. Why 10? Why not 100?

The answer is in the docs:

The watch listener may change the model, which may trigger other listeners to fire. This is achieved by rerunning the watchers until no changes are detected. The rerun iteration limit is 10 to prevent an infinite loop deadlock.

When you see this happening, it means you are changing the model in such a way that Angular has to rerun the digest and fire the watches again. In your particular case you are calling a function that updates a counter, which is displayed on the page. When the counter value changes it runs the digest again, which calls the function that updates the counter, etc, etc.

Angular expects you (and indeed encourages you) to change the model and let the view respond to those changes, rather than the other way around.

这篇关于多次执行角度作用域函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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