When will Angular clear $ watch?

I understand that every model that I include in my opinion introduces a digest cycle and the $watch applied to it, since all Angular applications are basically single-page applications. But when will he clear $watch ?

For example, let's say that I have a view1.html page with the template {{view.name1}} . When I switch the route to the view2.html page using the {{view.name2}} template, is $watch on {{view.name1}} registered automatically or should I do it manually?

+6
source share
1 answer

This answer contains links to angular scopes source code,

Each area has a private $$watchers array:

  • When calling the $watch method, it pushes listeners in $$watchers , see Scope # $ watch .
  • With each $digest it iterates over all $$watchers , see Scope # $ digest .
  • When calling the $destroy scope method, it clears all the watchers, see Scope # $ destroy
  • Each area also translates $destroy all child areas, isolated or not, so you will never have an orphaned area.
  • angular listens for deletion and DOM node $destroy triggers for all areas of the directive (created in the $ compile service), see here

angular automatically calls $destroy in these cases:


You only need to call $destroy when you manually create the areas ( $new / $transclude ) and want them to be destroyed before their parent area.

ngView is probably a good example because you only have one element associated with it in your application, and that element (with its scope, which is often rootScope) is never destroyed. Thus, angular automatically creates a new child region ( $new ) when it enters the route, and calls $destroy on it when it exists, thus clearing all the observers that were created by this route.

From Scope # $ new docs :

$ destroy () must be called in the region when it is necessary for the region and its child regions must be constantly separated from the parent and thus stop participating in detecting changes and listening to the notification model by calling.

From $ compile - bookmark closing functions :

if you intend to add and remove the broadcast content manually in your directive (by calling the forwarding function to get the DOM and calling element.remove () to remove it), then you are also responsible for calling $ destroy in the broadcast area.


Take this, as a rule, if you manually created a region (with $new or $transclude ) and you no longer need it, but you need to manually destroy it.

+7
source

Source: https://habr.com/ru/post/977945/


All Articles