gpt4 book ai didi

angularjs - Controller 与指令的区别以及何时使用?

转载 作者:行者123 更新时间:2023-12-04 16:59:34 25 4
gpt4 key购买 nike

我正在努力理解 Controller 的目的是什么。我知道这是您引用事物的方式,但是由于您可以将其放入指令中,因此是否存在过一种情况,您希望将 ng-controller 用于 html 中的特定部分,而不是创建具有内置 Controller 的指令在?

最佳答案

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?


是的,绝对是的。
  • 当目标是操作 DOM 时使用指令。
  • 当您想要创建可重用组件时,请使用指令。
  • 当您只需要将值绑定(bind)到 DOM 时,请使用 Controller 。

  • 对于这两种方法中的任何一种,可能还有一百种其他情况,但我相信这应该足以证明使用其中一种方法是合理的。
    至于两者之间的区别,请查看@yvesmancera 已经指出您的问题( 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.

    关于angularjs - Controller 与指令的区别以及何时使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31481000/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com