arp arp - 3 months ago 14
AngularJS Question

Anguarjs Directive or Controller to seperate views components

I'm trying to learn Angularjs (1.5) I have already understood the concept of filters and services and I've also understood logic behind controllers and directives too. But when I started to write my first application, I couldn't distinguish whether I should split components of view in to Controllers or Directives. For example, I have a page like following;

<navigation-bar>
<menu></menu>
<search-box></search-box>
</navigation-bar>
<content>
<comments>
<comment></comment>
<comment></comment>
<comment></comment>
</comments>
</content>


Right now, I am creating Controller for each component with templateUrl, is this approach is correct or should I create directives instead ? If I should create directives, How should I manage the Comments section which will repeat each comment with the data gathered from a service. Is it right to create a CommentsController and Comment directive for repeating content ?

Thanks in advance

Answer

Firstr of you should know about Directives and Controllers.
Directives:- extend HTML with custom attributes and elements.
Controllers:- the business logic behind views.

So if you have to write only business logic then you can write in controller and if you want to access service data then inject service in controller.
I controller, You can write logic to save data, You can write rendering logic, then data handling and processing logic. for such logics there is no need of custom directive.

But yes when you have to customise your view that time you should use custom directives.
For ex.
- Suppose you want to show selection widget in your form.
- If You want to go in details of any field or if you want to show customise view for particular fields that time use custom directives.

In Your case,

<navigation-bar>
  <menu></menu>
  <search-box></search-box>
</navigation-bar>
<content>
  <comments>
    <comment></comment>
    <comment></comment>
    <comment></comment>
  </comments>
</content>

In above code create HTML and use it with controller but if you want to cutomise your search box or comment then only add custom directive for that otherwise there is no need to use custom directive.