gpt4 book ai didi

javascript - Angular JS : What is the need of the directive’s link function when we already had directive’s controller with scope?

转载 作者:IT老高 更新时间:2023-10-28 13:14:55 26 4
gpt4 key购买 nike

我需要对范围和模板执行一些操作。看来我可以在 link 函数或 controller 函数中做到这一点(因为两者都可以访问范围)。

什么时候我必须使用 link 函数而不是 Controller ?

angular.module('myApp').directive('abc', function($timeout) {
return {
restrict: 'EA',
replace: true,
transclude: true,
scope: true,
link: function(scope, elem, attr) { /* link function */ },
controller: function($scope, $element) { /* controller function */ }
};
}

另外,我知道 link 是非 Angular 世界。所以,我可以使用 $watch$digest$apply

link函数的意义是什么,当我们已经有了 Controller 的时候?

最佳答案

在我与 link初始斗争之后和 controller函数并阅读了很多关于它们的内容,我想现在我有了答案。

首先让我们了解

简而言之, Angular Directive(指令)是如何工作的:

  • 我们从一个模板开始(作为一个字符串或加载到一个字符串)

    var templateString = '<div my-directive>{{5 + 10}}</div>';

  • 现在,这个 templateString被包装为 Angular 元素

    var el = angular.element(templateString);

  • el , 现在我们用 $compile 编译它取回 link 功能。

    var l = $compile(el)

    这就是发生的事情,

    • $compile遍历整个模板并收集它识别的所有指令。
    • 发现的所有指令都是递归编译及其link收集函数。
    • 那么,所有的link函数被包装在一个新的 link 中函数并返回为 l .
  • 最后,我们提供scope函数到此l (link) 函数,它使用 scope 进一步执行包装的链接函数及其对应的元素。

    l(scope)

  • 这增加了 template作为 DOM 的新节点并调用 controller它将其 watch 添加到与 DOM 中的模板共享的 范围

enter image description here

比较 compile vs link vs controller:

  • 每个指令只编译一次,link 函数被保留以供重复使用。因此,如果有适用于指令的所有实例的东西,应该在指令的 compile 内执行。功能。

  • 现在,编译后我们有 link在将 template 附加到 DOM 时执行的函数。因此,我们执行特定于指令每个实例的所有操作。例如:附加事件根据范围改变模板

  • 最后,controller 可以在指令作用于 DOM 时提供实时和 react 性。 (附上后)。因此:

    (1) 使用链接设置 View [V](即模板)后。 $scope是我们的 [M] 和 $controller是我们在 M V C

    中的 [C]

    (2) 通过设置监视来利用 2-way$scope 的绑定(bind)。

    (3) $scope预计将在 Controller 中添加监视,因为这是在运行时监视模板的内容。

    (4) 最后,controller也用于能够在相关指令之间进行通信。 (如 myTabs 中的示例 https://docs.angularjs.org/guide/directive )

    (5) 确实,我们可以在 link 中完成所有这些操作。功能也一样,但它是关于关注点分离

因此,最后我们得到了完美契合所有部分的以下内容:

enter image description here

关于javascript - Angular JS : What is the need of the directive’s link function when we already had directive’s controller with scope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20018507/

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