这是我今天在学习 Angular 时根据示例设置的一些简单示例代码。
几个问题:
它如何知道运行
categoryFilterFn
。我猜测任何绑定(bind)到 html View 和$scope
的内容都会以某种方式“以防万一”发生变化而执行。为什么过滤器运行两次?如果运行该示例,您将看到四种产品的八个控制台语句。即使我将其全部移至一个 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/