3
votes

There are a couple of popular recursive angular directive Q&A's out there. An elegant solution is to abstracting the recursion functionality into a service And call it at directive 'compile' phase :

Stack Overflow Answer

What is the best approach if I want to use the same concept in the new Angular 1.5 .component() instead of .directive()?

2
This is a little too broad of a question... you should try it in 1.5 and see what you think. And you have specific problems, ask in SO :). - ajmajmajma
@ajmajmajma I don't understand 2 things: 1) Why you gave me downvote. 2)If you understood my question. 1.5 .component() does not have 'compile'... I think I'm beeing specific in my question - Pedro Justo
I did not downvote, however there are many ways to achieve recursion via a directive or component hence this is a broad and possibly opinion based question. You should give it a shot at least and show code if there are problems or questions. - ajmajmajma
So, How can I compile all the nested contents which are supposed to be the 'same' component? Recursively. I know How I can achieve that with .directive(), I want to know How to apply same concept using 1.5 .component() - Pedro Justo
Either don't rely on compile - have the template itself recurse based on the passed data or just stick to directive(). I believe component exposes a few other methods you can work with if you are absolutely stuck with using component. - ajmajmajma

2 Answers

10
votes

Not sure what the confusion is... this is extremely simple to pull off. Below is an example of a recursive component.

angular
.module('app', [])
.component('recursed', {
  template: [
    '<div class="container">',
      '<div>Contains {{$ctrl.depth}} layers</div>',
      '<recursed depth="$ctrl.depth-1" ng-if="$ctrl.depth"></recursed>',
    '</div>'
  ].join(''),
  bindings: {
    depth: '<'
  }
})
.container {
  padding: 5px;
  border: 1px solid #ececec;
  border-radius: 4px;
}
<script src="//unpkg.com/angular@1.5.8/angular.js"></script>
<div ng-app="app">
  <h1>Recursion</h1>
  <recursed depth="5"></recursed>
</div>
2
votes

Components are supposed to be more strict than directives (for simple directives).

They do not expose compile function.

this is from the docs:

When not to use Components:

for directives that rely on DOM manipulation, adding event listeners etc, because the compile and link functions are unavailable when you need advanced directive definition options like priority, terminal, multi-element when you want a directive that is triggered by an attribute or CSS class, rather than an element

In other words - components don't replace directives, they inherit from them making it easier to build simple directives. You can still use directives to the task. They are not deprecated.