Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit cdf6fb1

Browse files
mprobstIgorMinar
authored andcommitted
feat($compile): support modifying the DOM structure in postlink fn
Support modifying the DOM structure in the post link function of a directive by creating a defensive copy of the node list, as opposed to a live DOM list. This is useful for directives to actually replace their entire DOM fragment, e.g. with the HTML fragment generated by a 3rd party component (Closure, Bootstrap ...). Fix the indentation of the compileNodes function (was one too little).
1 parent c909f49 commit cdf6fb1

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/ng/compile.js

+9-3
Original file line numberDiff line numberDiff line change
@@ -394,10 +394,16 @@ function $CompileProvider($provide) {
394394
return linkFnFound ? compositeLinkFn : null;
395395

396396
function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
397-
var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn;
397+
var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn, i, ii, n;
398398

399-
for(var i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
400-
node = nodeList[n];
399+
// copy nodeList so that linking doesn't break due to live list updates.
400+
var stableNodeList = [];
401+
for (i = 0, ii = nodeList.length; i < ii; i++) {
402+
stableNodeList.push(nodeList[i]);
403+
}
404+
405+
for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
406+
node = stableNodeList[n];
401407
nodeLinkFn = linkFns[i++];
402408
childLinkFn = linkFns[i++];
403409

test/ng/compileSpec.js

+19
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,25 @@ describe('$compile', function() {
285285
expect(log).toEqual('LOG; LOG');
286286
});
287287
});
288+
289+
290+
it('should allow modifying the DOM structure in post link fn', function() {
291+
module(function() {
292+
directive('removeNode', valueFn({
293+
link: function($scope, $element) {
294+
$element.remove();
295+
}
296+
}));
297+
});
298+
inject(function($compile, $rootScope) {
299+
element = jqLite('<div><div remove-node></div><div>{{test}}</div></div>');
300+
$rootScope.test = 'Hello';
301+
$compile(element)($rootScope);
302+
$rootScope.$digest();
303+
expect(element.children().length).toBe(1);
304+
expect(element.text()).toBe('Hello');
305+
});
306+
})
288307
});
289308

290309
describe('compiler control', function() {

0 commit comments

Comments
 (0)