如果要进行这种通信,则需要
require在child指令中使用。这将需要父级,
controller因此您需要一个
controller具有希望子级指令使用的功能的父级。
例如:
app.directive('parent', function() { return { restrict: 'E', transclude: true, template: '<div>{{message}}<span ng-transclude></span></div>', controller: function($scope) { $scope.message = "Original parent message" this.setMessage = function(message) { $scope.message = message; } } }});控制器中有一条消息
$scope,您可以更改它。
为什么
$scope一对一使用
this?您无法访问
$scopechild指令中的in,因此您需要
this在函数中使用,以便您的child指令能够对其进行调用。
app.directive('child', function($timeout) { return { restrict: 'E', require: '^parent', link: function(scope, elem, attrs, parentCtrl) { $timeout(function() { parentCtrl.setMessage('I am the child!') }, 3000) } }})如您所见,该链接使用parentCtrl接收第四个参数(或者如果有多个数组,则为数组)。在这里,我们只等待3秒钟,直到调用在父控制器中定义的方法以更改其消息。
在此处实时查看:http :
//plnkr.co/edit/72PjQSOlckGyUQnH7zOA?p=preview



