Fre*_*ind 18 angularjs angularjs-directive
在本文档中:http://docs.angularjs.org/guide/directive,它表示指令可以通过控制器相互通信.
controller - 控制器构造函数.控制器在预链接阶段之前被实例化,如果它们按名称请求它,则与其他指令共享(请参阅require属性).这允许指令彼此通信并增强彼此的行为.
我不太了解,他们如何与控制器沟通?它有任何示例或演示吗?
And*_*ahl 34
也许您会混淆使用指令控制器发生路由更改时创建的控制器.该部分仅讨论指令控制器,因此该部分的含义是,如果在同一HTML元素上有两个指令,则它们可以通过要求彼此控制器进行通信.
一个很好的例子是你创建一个需要与之通信的指令ng-model
.由于ng-model
暴露了控制器,您可以像这样要求:
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
}
}
});
Run Code Online (Sandbox Code Playgroud)
和HTML:
<input type="text" ng-model="myModel" my-directive>
Run Code Online (Sandbox Code Playgroud)
您的指令可以通过在指令函数返回的对象中实现它来公开控制器,如下所示:
myApp.directive('myDirective1', function() {
return {
link: function($scope, elem, attrs) {
},
controller: function() {
this.sayHello = function() {
alert("hello!");
}
}
}
});
myApp.directive('myDirective2', function() {
return {
require: 'myDirective1',
link: function($scope, elem, attrs, myDirective1Ctrl) {
myDirective1Ctrl.sayHello();
}
}
});
Run Code Online (Sandbox Code Playgroud)
和HTML:
<input type="text" my-directive2 my-directive1>
Run Code Online (Sandbox Code Playgroud)
您还可以通过编写来从父指令中获取指令控制器require: '^myParentDirective'
,如下所示:
myApp.directive('myDirective1', function() {
return {
link: function($scope, elem, attrs) {
},
controller: function() {
this.sayHello = function() {
alert("hello!");
}
}
}
});
myApp.directive('myDirective2', function() {
return {
require: '^myDirective1',
link: function($scope, elem, attrs, myDirective1Ctrl) {
myDirective1Ctrl.sayHello();
}
}
});
Run Code Online (Sandbox Code Playgroud)
和HTML:
<div my-directive1>
<div my-directive2></div>
</div>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6634 次 |
最近记录: |