user1620696
user1620696

Reputation: 11375

When to use directives in angular?

I'm working with angular js and there's one thing I didn't fully understand yet. I know what directives are: they are "additional features" that we add to HTML that can be used as elements, attributes, comments or classes and that can change completely the markup there by some other thing rendered by angular or can add functionality with the link function.

That's fine, but when to use directives? I know that if we want to represent on screen some domain specific object then this is one possible candidate for a directive, or when we want to add functionality to some HTML element (like slider functionality to an input) then we use a directive. But what about other cases? What about when we want to manipulate the DOM to, for instance, activate the functionality of a sidebar or thing like that? Directives are used for this to?

How do when know when to use a directive in angular?

Upvotes: 3

Views: 162

Answers (2)

Gil Birman
Gil Birman

Reputation: 35900

Some directive rules of thumbs:

  • If you plan on adding the same markup-based functionality more than once, create a directive (but if it's simple enough, just use ng-include).
  • If you need to modify the way an ng-modeled input field validates, formats, or parses, create a directive that requires ngModel.
  • If you want to make writing unit tests easier for a specific piece of markup, write a directive.
  • If you come from a jQuery background and instinctively feel like using $('.jquery-style-selectors') from your controller, instead write a group of directives where the child directive(s) require the parent directive(s) and communicate via the directive controller(s).

Upvotes: 2

Braulio
Braulio

Reputation: 1728

I think about directives when I face one of this two scenarios:

  • Custom control: I need to implement a custom control, that probably I will reuse in other parts of my app or even other projects.
  • Custom Validations: AngularJS provides a limited set of validations (e.g. ngRequired, RegEx...), but for sure you will need to implement your custom logic validations. I prefer to implement that validations in directives (reuse, SRP, easy to be tested isolated) rather to overload the controller with that logic.

Upvotes: 4

Related Questions