Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between and when to use controllers vs directives?

Tags:

angularjs

I'm struggling to understand what the purpose of a controller is. I understand that it is how you reference things but since you can throw it in a directive, is there ever a scenario where you would want to use ng-controller for a specific section in your html rather than creating a directive that has a controller built in?

like image 267
mcrav Avatar asked Jul 17 '15 16:07

mcrav


1 Answers

is there ever a scenario where you would want to use ng-controller for a specific section in your html rather than creating a directive that has a controller built in?

Yes, absolutely yes.

  • Use a directive when the goal is to manipulate the DOM.
  • Use a directive when you want to create a reusable component.
  • Use a controller when all you need is to bind values to the DOM.

There's probably a hundred other cases that could be made for either of the two approaches, but I believe this should be enough to justify the use of one over the other.

As for the differences between the two, look at the question that @yvesmancera already pointed you to (angularjs-directives-vs-controllers).

In Angular, a Controller is defined by a JavaScript constructor function that is used to augment the Angular Scope.

When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be created and made available as an injectable parameter to the Controller's constructor function as $scope.


At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.

like image 126
Kasper Lewau Avatar answered Oct 12 '22 22:10

Kasper Lewau