从您的示例中,指令结构不是父子。因此,您无法通过其控制器共享方法。我会用 $rootScope.$broadcast 。 (看到 DOCS )
$rootScope.$broadcast
一条指令称:
$rootScope.$broadcast('someEvent', [1,2,3]);
第二个指令侦听:
scope.$on('someEvent', function(event, mass) { console.log(mass)} );
演示 的 小提琴 强>
固定指令:
app.directive("firstDir", function ($rootScope) { return { restrict: 'E', link: function (scope, element, attrs) { scope.dataToPass = 'empty'; scope.doClick = function (valueToPass) { scope.dataToPass = valueToPass; $rootScope.$broadcast('someEvent', { data: valueToPass }); } } }; }); app.directive("secondDir", function () { return { restrict: 'E', link: function (scope, element, attrs) { scope.receivedData = 'none'; scope.$on('someEvent', function (event, result) { scope.receivedData = result.data; }); } } });
我正在使用的是导出指令控制器。假设我有以下指令:
app.directive('mainDirective', function () { return { require: 'mainDirective' restrict: 'E', scope: { controller: '=' }, controller: [ '$scope', function ($scope) { // controller methods this.doSomething = function () { ... }, $scope.controller = this return this } ], link: function (scope, element, attrs, mainDirective) { // some linking stuff } } });
我的HTML看起来像这样:
<main-directive controller="mainDirective"></main-directive> <sub-directive main-directive="mainDirective"></sub-directive>
如果我想从子指令控制main-directive,我可以轻松地从它的范围中获取它并做我想做的事......
app.directive('subDirective', function () { return { restrict: 'E', scope: { mainDirective: '=' } link: function (scope, element, attrs) { // do something with main directive scope.mainDirective.doSomething(); } } });