加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 指令如何通过控制器进行通信?

发布时间:2020-12-17 08:11:49 所属栏目:安全 来源:网络整理
导读:在本文档中: http://docs.angularjs.org/guide/directive表示指令可能由控制器相互通信。 controller – Controller constructor function. The controller is instantiated before the pre-linking phase and it is shared with other directives if they
在本文档中: http://docs.angularjs.org/guide/directive表示指令可能由控制器相互通信。

controller – Controller constructor function. The controller is instantiated before the pre-linking phase and it is shared with other directives if they request it by name (see require attribute). This allows the directives to communicate with each other and augment each other’s behavior.

我不明白,他们如何与控制器沟通?有没有任何示例或演示?

也许你对使用指令控制器发生路由更改时创建的控制器感到困惑。该部分只是在谈论指令控制器,所以该部分意味着如果您在同一个HTML元素上有两个指令,则可以通过要求彼此控制器进行通信。

一个很好的例子就是如果你创建一个需要与ng-model通信的指令。由于ng模型暴露了控制器,因此您可以要求它:

myApp.directive('myDirective',function() {
    return {
        require: 'ngModel',link: function($scope,elem,attrs,ngModelCtrl) {
            // Here you can listen to different DOM events,and
            // call ngModelCtrl when the model value needs to update
        }
    }
});

和HTML:

<input type="text" ng-model="myModel" my-directive>

您的指令可以通过在您的指令函数返回的对象中实现它来暴露控制器,如下所示:

myApp.directive('myDirective1',function() {
    return {
        link: function($scope,attrs) {

        },controller: function() {
            this.sayHello = function() {
                alert("hello!");
            }
        }
    }
});

myApp.directive('myDirective2',function() {
    return {
        require: 'myDirective1',myDirective1Ctrl) {
            myDirective1Ctrl.sayHello();
        }
    }
});

和HTML:

<input type="text" my-directive2 my-directive1>

您也可以通过编写require:’^ myParentDirective’来要求来自父指令的指令控制器,如下所示:

myApp.directive('myDirective1',function() {
    return {
        require: '^myDirective1',myDirective1Ctrl) {
            myDirective1Ctrl.sayHello();
        }
    }
});

和HTML:

<div my-directive1>
    <div my-directive2></div>
</div>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读