Skip to content

Commit aca8559

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 aca8559

File tree

3 files changed

+430
-30
lines changed

3 files changed

+430
-30
lines changed

Diff for: docs/content/guide/component.ngdoc

+24
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". These 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 have 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

Diff for: src/ng/compile.js

+82-4
Original file line numberDiff line numberDiff line change
@@ -293,9 +293,23 @@
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 (`<`) or interpolation (`@`) bindings are updated. The
300+
* `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
301+
* object of the form `{ currentValue: ..., previousValue: ... }`. Use this hook to trigger updates within a component
302+
* such as 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. Note that components have their `$onDestroy()` hooks called in
305+
* the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
306+
* components will have their `$onDestroy()` hook called before child components.
307+
* * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
308+
* function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
309+
* Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
310+
* they are waiting for their template to load asynchronously and their own compilation and linking has been
311+
* suspended until that occurs.
312+
*
299313
*
300314
* #### `require`
301315
* Require another directive and inject its controller as the fourth argument to the linking function. The
@@ -1215,6 +1229,24 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
12151229

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

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

@@ -2400,6 +2438,14 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
24002438
);
24012439
}
24022440

2441+
// Trigger $postLink lifecycle hooks
2442+
forEach(elementControllers, function(controller) {
2443+
var controllerInstance = controller.instance;
2444+
if (isFunction(controllerInstance.$postLink)) {
2445+
controllerInstance.$postLink();
2446+
}
2447+
});
2448+
24032449
// This is the function that is injected as `$transclude`.
24042450
// Note: all arguments are optional!
24052451
function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
@@ -2995,6 +3041,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
29953041
// only occurs for isolate scopes and new scopes with controllerAs.
29963042
function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
29973043
var removeWatchCollection = [];
3044+
var changes;
29983045
forEach(bindings, function initializeBinding(definition, scopeName) {
29993046
var attrName = definition.attrName,
30003047
optional = definition.optional,
@@ -3010,6 +3057,8 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
30103057
}
30113058
attrs.$observe(attrName, function(value) {
30123059
if (isString(value)) {
3060+
var oldValue = destination[scopeName];
3061+
recordChanges(scopeName, value, oldValue);
30133062
destination[scopeName] = value;
30143063
}
30153064
});
@@ -3081,6 +3130,8 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
30813130
destination[scopeName] = parentGet(scope);
30823131

30833132
removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newParentValue) {
3133+
var oldValue = destination[scopeName];
3134+
recordChanges(scopeName, newParentValue, oldValue);
30843135
destination[scopeName] = newParentValue;
30853136
}, parentGet.literal);
30863137

@@ -3101,6 +3152,33 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
31013152
}
31023153
});
31033154

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

0 commit comments

Comments
 (0)