Question

So here is some simple sample code I setup from an example today while I was learning Angular.

jsFiddle link

Couple questions:

  1. 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.

  2. 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.

Était-ce utile?

La solution

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.

Yes the Angular digest cycle does dirty checking to see if anything has changed. It does this over the watch queue (and things are put in the watch queue based on if they are bound in the 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.

Again, Angular uses dirty checking (here is a good article about it). Essentially, during the start of a digest cycle the watched value is resolved. Then, at the end of the digest cycle, the value is resolved again (this is the second call). If the values do not match, the UI is replaced with the new values. In very simple terms, this is how the two-way binding works.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top