Difference between and when to use controllers versus directives?

I am struggling to understand what the purpose of the controller is. I understand this is how you are referencing things, but since you can cast it in a directive, is there ever a scenario where you would like to use ng-controller for a specific section in your html rather than create a directive with built-in controller in?

+3


source to share


1 answer


Is there ever a scenario where you would like to use ng-controller for a specific section in html instead of creating a directive with an inline controller?

Yes, absolutely yes.

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

There are probably hundreds more other cases that could be done for either of the two approaches, but I believe that should be enough to justify using one over the other.



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

In Angular, a controller is defined by a JavaScript constructor function that is used to enlarge Angular's scope.

When a controller is connected to the DOM via the ng-controller directive, Angular will instantiate a new Controller object using the specified controller constructor function. The new child scope will be created and available as an injection parameter to the controller 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 the HTML (HTML) compiler to the AngularJS compiler to associate the specified behavior with that DOM element, or even transform the DOM element and its children elements.

+6


source







All Articles