答案 0 :(得分:1)
您应该使用服务在它们之间进行通信。具体如何/你做什么取决于你的确切需求(你的帖子中没有足够的信息)。
旁注,我将您的点击处理程序更改为ng-click。
这是一个例子: http://plnkr.co/edit/I2TvvV?p=preview
<div search-result-filter></div>
<div search-result-header ng-click="doClick()"></div>
angular.module('mymodule', [])
.controller('mainCtrl', ['$scope',
function($scope) {
$scope.test = "main angular is working";
}
]).controller('searchResultFilterController', ['$scope', 'myService',
function($scope, myService) {
//do something with 'myService'
}
])
.directive('searchResultFilter', [
function() {
return {
replace: true,
controller: 'searchResultFilterController',
template: '<h1>this is the first directive</h1>'
};
}
])
.directive('searchResultHeader', ['myService',
function(myService) {
return {
replace: true,
template: '<button>clickme</button>',
link: function($scope, $elem, $attrs) {
$scope.doClick = function() {
myService.someFn();
};
}
};
}
])
.service('myService', function() {
this.someFn = function() {
alert('this is working');
};
});
答案 1 :(得分:1)
当指令相关时,您应该使用require
:如手风琴和手风琴项目。
要在范围之间进行通信,您应该尝试$ on,$ emit,$ broadcast。在您的情况下,您需要将rootScope注入您的指令,并从rootScope广播一个事件:
.directive('searchResultHeader',
function($rootScope) { //inject rootScope
return {
replace: true,
template: '<button>clickme</button>',
link: function($scope, $elem, $attrs) {
$elem.on('click', function() {
$rootScope.$broadcast("someEvent"); //broadcast an event to all child scopes.
});
}
};
}
);
对该活动感兴趣的任何范围都可以使用$ on订阅它:
function($scope) {
$scope.$on("someEvent", function() {
alert('this is working');
});
}
使用事件是一种创建解耦系统的方法。