2

Let's say I need to add a Tag functionality similar to the one offered by StackExchange to my website: I have an input bar filled with selected tags, when I type something a list of suggestions appear. Pretty standard stuff.

I would do the following:

  • create a Tag module
  • add a Tag controller that uses a Service to fetch tags, and declares methods like addTag, removeTag, findSimilarTags, .. --> i.e. it uses the $scope model data
  • add a Directive with a template specifying the layout of my Tag module, with methods that call the controller methods, e.g. add(), remove(), ..

this way I could differentiate between events coming from the user (e.g. add() calls internally addTag()) and from other parts of the code (e.g. a watcher that internally calls addTag() when something happens).

In summary:

  • controller: handles data from the model (ev. using services)
  • directive: handles DOM manipulation and events, uses the controller to do the actual work

Does this make sense? Why does Google separate completely directives from controllers? Should directives be more "smart" and handle data directly?

scniro
  • 16,844
  • 8
  • 62
  • 106
fusio
  • 3,595
  • 6
  • 33
  • 47

1 Answers1

0

Directives as the name suggest.. They are used for doing some manipulation over the data and send back it to controllers.. It is very similer to functions. Directives is used for better modularity of the code.. It removes unstructure code from controller. Ya directive can also handles data directly but it is not appritiated.