2

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?

developer033
  • 24,267
  • 8
  • 82
  • 108
mpasko256
  • 811
  • 14
  • 30
  • You can see the link https://toddmotto.com/angular-1-5-lifecycle-hooks maybe help you. – Feras Al Sous Aug 14 '18 at 14:20
  • 1
    @FerasAlSous I think this does not applies here because the OP is asking for these hooks when the controller is created using the `ng-controller` directive, not using the `.component` approach. – lealceldeiro Aug 14 '18 at 14:30

1 Answers1

2

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
});
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80