angularjs - Difference between and when to use controllers vs directives? -


i'm struggling understand purpose of controller is. understand how reference things since can throw in directive, there ever scenario want use ng-controller specific section in html rather creating directive has controller built in?

is there ever scenario want use ng-controller specific section in html rather creating directive has controller built in?

yes, absolutely yes.

  • use directive when goal manipulate dom.
  • use directive when want create reusable component.
  • use controller when need bind values dom.

there's hundred other cases made either of 2 approaches, believe should enough justify use of 1 on other.

as differences between two, @ question @yvesmancera pointed (angularjs-directives-vs-controllers).

in angular, controller defined javascript constructor function used augment angular scope.

when controller attached dom via ng-controller directive, angular instantiate new controller object, using specified controller's constructor function. new child scope created , made available injectable parameter controller's constructor function $scope.


at high level, directives markers on dom element (such attribute, element name, comment or css class) tell angularjs's html compiler ($compile) attach specified behavior dom element or transform dom element , children.


Comments