Search code examples
angularjsangular-controllerangular-lifecycle-hooks

AngularJS pure ng-controller lifecycle hooks


Suppose a pure AngualrJS (1.6.x) controller declared using ng-controller directive (in contrary to a component controller).

Does it have lifecycle hooks like $onInit or $onDestroy?


Solution

  • According to the section Scope Life Cycle in the scope documentation (v1.6.10) there are not such hooks (using the ng-controller approach).

    The scope lifecycle would go like this:

    1. Creation

    The root scope is created during the application bootstrap by the $injector. During template linking, some directives create new child scopes.

    1. Watcher registration

    During template linking, directives register watches on the scope. These watches will be used to propagate model values to the DOM.

    1. Model mutation

    For mutations to be properly observed, you should make them only within the scope.$apply(). AngularJS APIs do this implicitly, so no extra $apply call is needed when doing synchronous work in controllers, or asynchronous work with $http, $timeout or $interval services.

    1. Mutation observation

    At the end of $apply, AngularJS performs a $digest cycle on the root scope, which then propagates throughout all child scopes. During the $digest cycle, all $watched expressions or functions are checked for model mutation and if a mutation is detected, the $watch listener is called.

    1. Scope destruction

    When child scopes are no longer needed, it is the responsibility of the child scope creator to destroy them via scope.$destroy() API. This will stop propagation of $digest calls into the child scope and allow for memory used by the child scope models to be reclaimed by the garbage collector.


    Of course, alternatively, you can always use $rootScope.Scope#$on for listening for changes.

    Examples:

    $scope.$on('my-custom-event', function () {
    // some code to execute when my-custom-event is fired
    });
    
    $scope.$on('$destroy', function () {
    // some code to execute when the scope is destroyed
    });