Difference between and when to use controllers vs directives?

前端 未结 1 691
时光取名叫无心
时光取名叫无心 2021-01-13 11:15

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

1条回答
  •  迷失自我
    2021-01-13 11:42

    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.

    0 讨论(0)
提交回复
热议问题