javascript - 为什么 Angular 过滤器运行两次?

标签 javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

这是我今天在学习 Angular 时根据示例设置的一些简单示例代码。

jsFiddle link

几个问题:

  1. 它如何知道运行categoryFilterFn。我猜测任何绑定(bind)到 html View 和 $scope 的内容都会以某种方式“以防万一”发生变化而执行。

  2. 为什么过滤器运行两次?如果运行该示例,您将看到四种产品的八个控制台语句。即使我将其全部移至一个 Controller 中,它仍然会执行此操作。

最佳答案

How does it know to run categoryFilterFn. I'm guessing anything binded to the html view and the $scope is somehow just executed "in case" there are changes.

是的,Angular 摘要循环会进行脏检查以查看是否有任何更改。它通过监视队列执行此操作(并且根据事物是否绑定(bind)在 UI 中将事物放入监视队列中)。

Why does the filter run twice? If you run the example you will see eight console statements for the four products. Even if I move it all into one controller it still does this.

同样,Angular 使用脏检查 ( here is a good article about it )。本质上,在摘要周期开始期间,观察值被解析。然后,在摘要循环结束时,再次解析该值(这是第二次调用)。如果值不匹配,UI 将替换为新值。简单来说,这就是双向绑定(bind)的工作原理。

关于javascript - 为什么 Angular 过滤器运行两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23391453/

相关文章:

javascript - Socket.io/ARI 错误 : Emit Alert

javascript - 迭代时动态获取图像数据 URL

android - 尝试更改 Ionic 应用程序状态栏文本颜色

angularjs - 在 AngularJs 中克隆元素(绑定(bind)和所有)

javascript - angularjs 从一个巨大的列表中更新单个元素

javascript - 解析 html 元素中的 data-i18n 属性

javascript - 函数代理 .toString() 错误

javascript - Angular - 服务返回值,但不在 app.config 中路由

javascript - AngularJS 注入(inject)器问题

javascript - Angular 指令父范围