Skip to content

Commit 6bb268f

Browse files
author
Mark Lagendijk
committed
First commit
1 parent c3ef9e5 commit 6bb268f

File tree

2 files changed

+72
-2
lines changed

2 files changed

+72
-2
lines changed

README.md

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,33 @@
1-
angular-recursion-helper
2-
========================
1+
# angular-recursion-helper
32

43
A service which makes it easy possible to have recursive Angular directives.
4+
5+
## Why
6+
When an Angular directive calls itself, Angular gets into an endless loop. This service provides the logic needed to work around this.
7+
8+
## Usage
9+
The service is used by injecting it into your directive and using it in the directives' compile function. The following example shows this. See [this fiddle](http://jsfiddle.net/xUsCc/34/) to see this example running.
10+
11+
``` javascript
12+
module.directive("tree", function(RecursionHelper) {
13+
return {
14+
restrict: "E",
15+
scope: {family: '='},
16+
template:
17+
'<p>{{ family.name }}{{test }}</p>'+
18+
'<ul>' +
19+
'<li ng-repeat="child in family.children">' +
20+
'<tree family="child"></tree>' +
21+
'</li>' +
22+
'</ul>',
23+
compile: function(element) {
24+
return RecursionHelper.compile(element, function(scope, iElement, iAttrs, controller, transcludeFn){
25+
// Define your normal link function here.
26+
// Alternative: instead of passing a function,
27+
// you can also pass an object with
28+
// a 'pre'- and 'post'-link function.
29+
});
30+
}
31+
};
32+
});
33+
```

recursionhelper.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
module.factory('RecursionHelper', ['$compile', function($compile){
2+
return {
3+
/**
4+
* Manually compiles the element, fixing the recursion loop.
5+
* @param element
6+
* @param [link] A post-link function, or an object with function(s) registered via pre and post properties.
7+
* @returns An object containing the linking functions.
8+
*/
9+
compile: function(element, link){
10+
// Normalize the link parameter
11+
if(angular.isFunction(link)){
12+
link = { post: link };
13+
}
14+
15+
// Break the recursion loop by removing the contents
16+
var contents = element.contents().remove();
17+
var compiledContents;
18+
return {
19+
pre: (link && link.pre) ? link.pre : null,
20+
/**
21+
* Compiles and re-adds the contents
22+
*/
23+
post: function(scope, element){
24+
// Compile the contents
25+
if(!compiledContents){
26+
compiledContents = $compile(contents);
27+
}
28+
// Re-add the compiled contents to the element
29+
compiledContents(scope, function(clone){
30+
element.append(clone);
31+
});
32+
33+
// Call the post-linking function, if any
34+
if(link && link.post){
35+
link.post.apply(null, arguments);
36+
}
37+
}
38+
};
39+
}
40+
};
41+
}]);

0 commit comments

Comments
 (0)