angular js scope

Like other angular newbies, I'm trying to understand what Scope means in angular js.

Scope is a complex concept in Angular js because the angular framework manages scope for you
e.g.
- each time you navigate to a controller then that controller is created and a new scope created for it
that scope inherits prototypal from its parent scope all the way up to the top level root scope (scope is created for a number of built in ng-* as well as custom directives too)
- when you navigate away from that controller to a page without that controller then the controller and its scope are destroyed; you can listen to controller destroy event $destroy (snippet below)
- angular provides framework properties $scope and $rootScope
- each $scope has a $parent which allows you access the parent scope, all the way up to root scope; this can be handy for debugging up the scope chain

This is a really useful tutorial about scope

And the answer here is informative about controllers and scope


We discovered a memory leak in our app because controllers were adding themselves to:
$rootScope.$on(eventId, callback)
...but $rootScope is not destroyed between pages as Controller $scope is
...thus the Controllers were not destroyed as they should have been (because the $on code had a reference to them)
..thus as you went in and out of the page with the Controller there are more and more controller instances actively listening to the event (bad)

Instead the following should have been used:
$scope.$on(eventId, callback)

...that way when $scope is destroyed, the reference is released and controller can be garbage collected (and not hang around)


on destroy snippet for a controller

$scope.$on('$destroy', function() {
$log.debug("MessagingController is being destroyed")
})

Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more