【发布时间】:2015-03-22 17:35:33
【问题描述】:
我需要调用一个属于我的 Angular 应用程序中使用的 ng 指令的 $scope 的函数。
假设指令是这样定义的:
.directive('my-directive', ['$document', '$timeout', function ($document, $timeout) {
return {
restrict: 'E',
replace: true,
scope: {
// ....
},
controller: ['$scope', function ($scope) {
$scope.myFunction= function (mouseEnter) {
// ...
};
}
};
}]);
我需要从我的控制器(我们称之为 my-controller)调用 myFunction,这是放置我的指令的视图的控制器。
有可能吗? (最终修改指令)
编辑:提供的已经回答的问题(建议编辑)与我的类似,因为我不清楚,或者它显然没有解决我提出的具体问题。
编辑 2:从 Dan M. answer 开始(不考虑 mouseenter/mouseleave。只是试图让两个控制器相互通信),我通过$rootScope(因为两个控制器之间没有父子关系)by:
console.log("let's broadcast the event.."); // this is printed
$rootScope.$broadcast('callDirectiveControllersFunction'); // I even tried with $scope in place of $rootScope and $emit in place of $broadcast
并通过以下方式接收它(在指令的控制器内):
var myFunction = function(){
// ...
}
$scope.$on('callDirectiveControllersFunction', function (){
console.log("event received"); // this is not printed
callMyFunction();
});
// I even tried using $rootScope in place of $scope
但是在没有(见代码中的 cmets)事件被接收
【问题讨论】:
-
我在问之前看到了那个答案。但是我不清楚,似乎给我的(简单)问题增加了一定程度的复杂性
标签: javascript angularjs angular-directive