Skip to content

Commit 5450d24

Browse files
feat($compile): add more lifecycle hooks to directive controllers
This change adds in the following new lifecycle hooks, which map in some way to those in Angular 2: * `$onChanges(changesObj)` - Called whenever one-way bindings are updated. The `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an object of the form `{ currentValue: ..., previousValue: ... }`. Use this hook to trigger updates within a component such as cloning the bound value to prevent accidental mutation of the outer value. * `$onDestroy` - Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources, watches and event handlers. * `$postLink` - Called after this controller's element and its children been linked. Similar to the post-link function this hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain `templateUrl` directives will not have been compiled and linked since they are waiting for their template to load asynchronously and their own compilation and linking has been suspended until that occurs. Closes angular#14127 Closes angular#14030 Closes angular#14020 Closes angular#13991 Closes angular#14302
1 parent e34ef23 commit 5450d24

File tree

3 files changed

+383
-31
lines changed

3 files changed

+383
-31
lines changed

docs/content/guide/component.ngdoc

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,30 @@ components should follow a few simple conventions:
147147
}
148148
```
149149

150+
- **Components have a well-defined lifecycle
151+
Each component can implement "lifecycle hooks", which are methods that will be called at certain points in the life
152+
of the component. The following hook methods can be implemented:
153+
154+
* `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
155+
had their bindings initialized (and before the pre & post linking functions for the directives on
156+
this element). This is a good place to put initialization code for your controller.
157+
* `$onChanges(changesObj)` - Called whenever one-way bindings are updated. The `changesObj` is a hash whose keys
158+
are the names of the bound properties that have changed, and the values are an object of the form
159+
`{ currentValue: ..., previousValue: ... }`. Use this hook to trigger updates within a component such as
160+
cloning the bound value to prevent accidental mutation of the outer value.
161+
* `$onDestroy` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
162+
external resources, watches and event handlers.
163+
* `$postLink` - Called after this controller's element and its children been linked. Similar to the post-link
164+
function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
165+
Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
166+
they are waiting for their template to load asynchronously and their own compilation and linking has been
167+
suspended until that occurs.
168+
This hook can be considered analogous to the `ngAfterViewInit` and `ngAfterContentInit` hooks in Angular 2.
169+
Since the compilation process is rather different in Angular 1 there is no direct mapping and care should
170+
be taken when upgrading.
171+
172+
By implementing these methods, you component can take part in its lifecycle.
173+
150174
- **An application is a tree of components:**
151175
Ideally, the whole application should be a tree of components that implement clearly defined inputs
152176
and outputs, and minimize two-way data binding. That way, it's easier to predict when data changes and what the state

src/ng/compile.js

Lines changed: 81 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -293,9 +293,21 @@
293293
* `true` if the specified slot contains content (i.e. one or more DOM nodes).
294294
*
295295
* The controller can provide the following methods that act as life-cycle hooks:
296-
* * `$onInit` - Called on each controller after all the controllers on an element have been constructed and
296+
* * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
297297
* had their bindings initialized (and before the pre & post linking functions for the directives on
298298
* this element). This is a good place to put initialization code for your controller.
299+
* * `$onChanges(changesObj)` - Called whenever one-way (`<`) bindings are updated. The `changesObj` is a hash
300+
* whose keys are the names of the bound properties that have changed, and the values are an object of the form
301+
* `{ currentValue: ..., previousValue: ... }`. Use this hook to trigger updates within a component such as
302+
* cloning the bound value to prevent accidental mutation of the outer value.
303+
* * `$onDestroy` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
304+
* external resources, watches and event handlers.
305+
* * `$postLink` - Called after this controller's element and its children have been linked. Similar to the post-link
306+
* function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
307+
* Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
308+
* they are waiting for their template to load asynchronously and their own compilation and linking has been
309+
* suspended until that occurs.
310+
*
299311
*
300312
* #### `require`
301313
* Require another directive and inject its controller as the fourth argument to the linking function. The
@@ -474,7 +486,7 @@
474486
*
475487
* * `iElement` - instance element - The element where the directive is to be used. It is safe to
476488
* manipulate the children of the element only in `postLink` function since the children have
477-
* already been linked.
489+
* already have been linked.
478490
*
479491
* * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
480492
* between all directive linking functions.
@@ -1215,6 +1227,24 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
12151227

12161228
var SIMPLE_ATTR_NAME = /^\w/;
12171229
var specialAttrHolder = document.createElement('div');
1230+
1231+
// The onChanges hooks should all be run together in a single digest
1232+
// When changes occur, the call to trigger their hooks will be added to this queue
1233+
var onChangesQueue;
1234+
1235+
// This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
1236+
function flushOnChangesQueue() {
1237+
// We must run this hook in an apply since the $$postDigest runs outside apply
1238+
$rootScope.$apply(function() {
1239+
for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
1240+
onChangesQueue[i]();
1241+
}
1242+
// Reset the queue to trigger a new schedule next time there is a change
1243+
onChangesQueue = undefined;
1244+
});
1245+
}
1246+
1247+
12181248
function Attributes(element, attributesToCopy) {
12191249
if (attributesToCopy) {
12201250
var keys = Object.keys(attributesToCopy);
@@ -2360,10 +2390,16 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
23602390
}
23612391
});
23622392

2363-
// Trigger the `$onInit` method on all controllers that have one
2393+
// Handle the init and destroy lifecycle hooks on all controllers that have them
23642394
forEach(elementControllers, function(controller) {
2365-
if (isFunction(controller.instance.$onInit)) {
2366-
controller.instance.$onInit();
2395+
var controllerInstance = controller.instance;
2396+
if (isFunction(controllerInstance.$onInit)) {
2397+
controllerInstance.$onInit();
2398+
}
2399+
if (isFunction(controllerInstance.$onDestroy)) {
2400+
controllerScope.$on('$destroy', function callOnDestroyHook() {
2401+
controllerInstance.$onDestroy();
2402+
});
23672403
}
23682404
});
23692405

@@ -2400,6 +2436,14 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
24002436
);
24012437
}
24022438

2439+
// Trigger $postLink lifecycle hooks
2440+
forEach(elementControllers, function(controller) {
2441+
var controllerInstance = controller.instance;
2442+
if (isFunction(controllerInstance.$postLink)) {
2443+
controllerInstance.$postLink();
2444+
}
2445+
});
2446+
24032447
// This is the function that is injected as `$transclude`.
24042448
// Note: all arguments are optional!
24052449
function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
@@ -2995,6 +3039,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
29953039
// only occurs for isolate scopes and new scopes with controllerAs.
29963040
function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
29973041
var removeWatchCollection = [];
3042+
var changes;
29983043
forEach(bindings, function initializeBinding(definition, scopeName) {
29993044
var attrName = definition.attrName,
30003045
optional = definition.optional,
@@ -3010,6 +3055,8 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
30103055
}
30113056
attrs.$observe(attrName, function(value) {
30123057
if (isString(value)) {
3058+
var oldValue = destination[scopeName];
3059+
recordChanges(scopeName, value, oldValue);
30133060
destination[scopeName] = value;
30143061
}
30153062
});
@@ -3081,6 +3128,8 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
30813128
destination[scopeName] = parentGet(scope);
30823129

30833130
removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newParentValue) {
3131+
var oldValue = destination[scopeName];
3132+
recordChanges(scopeName, newParentValue, oldValue);
30843133
destination[scopeName] = newParentValue;
30853134
}, parentGet.literal);
30863135

@@ -3101,6 +3150,33 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
31013150
}
31023151
});
31033152

3153+
function recordChanges(key, currentValue, previousValue) {
3154+
if (isFunction(destination.$onChanges) && currentValue !== previousValue) {
3155+
// If we have not already scheduled the top level onChangesQueue handler then do so now
3156+
if (!onChangesQueue) {
3157+
scope.$$postDigest(flushOnChangesQueue);
3158+
onChangesQueue = [];
3159+
}
3160+
// If we have not already queued a trigger of onChanges for this controller then do so now
3161+
if (!changes) {
3162+
changes = {};
3163+
onChangesQueue.push(triggerOnChangesHook);
3164+
}
3165+
// If the has been a change on this property already then we need to reuse the previous value
3166+
if (changes[key]) {
3167+
previousValue = changes[key].previousValue;
3168+
}
3169+
// Store this change
3170+
changes[key] = {previousValue: previousValue, currentValue: currentValue};
3171+
}
3172+
}
3173+
3174+
function triggerOnChangesHook() {
3175+
destination.$onChanges(changes);
3176+
// Now clear the changes so that we schedule onChanges when more changes arrive
3177+
changes = undefined;
3178+
}
3179+
31043180
return removeWatchCollection.length && function removeWatches() {
31053181
for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
31063182
removeWatchCollection[i]();

0 commit comments

Comments
 (0)