我需要调用一个函数,该函数属于我的Angular应用程序中使用的ng-directive的$ scope。
假设指令的定义如下:
.directive('my-directive', ['$document', '$timeout', function ($document, $timeout) {
return {
restrict: 'E',
replace: true,
scope: {
// ....
},
controller: ['$scope', function ($scope) {
$scope.myFunction= function (mouseEnter) {
// ...
};
}
};
}]);
我需要从我的控制器调用 myFunction (让我们称之为 my-controller ),这是我的指令所在的视图的控制器。
有可能吗? (最终修改指令)
编辑:已经回答的问题(建议编辑)与我的相似,我不清楚,或者它显然没有解决我提出的具体问题。
编辑2 :从Dan M.回答开始(不考虑鼠标中心/鼠标离开。只是试图让两个控制器相互通信),我通过以下方式将我的事件广播到我的指令控制器 $ rootScope (因为两个控制器之间没有父子关系):
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
但是无案例(请参阅代码中的评论)收到活动
答案 0 :(得分:1)
您可以在链接块中调用控制器功能。您还可以$emit指令中的事件并在控制器中监听它(可能有一个用例)。
您似乎想在mouseenter
上调用它。您可以通过绑定到指令链接中的mouseenter
事件来实现。问题是您需要$应用更改。
看看以下代码,其中包含所有3个示例:http://jsbin.com/cuvugu/8/。 (也粘贴在下面)
提示:您可能需要注意命名指令的方式。要将指令用作my-directive
,您需要将其命名为myDirective
。
var app = angular.module('App', []);
app.directive('myDirective', function () {
function directiveLink(scope){
scope.$emit('customEvent');
}
return {
restrict: 'EA',
scope: {},
link: directiveLink,
controller: function ($scope) {
$scope.bar = 'bar';
$scope.myFunction = function () {
$scope.bar = 'foobar1';
};
$scope.$on('customEvent', function (){
$scope.myFunction();
});
},
template: "Foo {{bar}}"
};
});
app.directive('anotherDirective', function () {
function directiveLink(scope){
scope.myFunction();
}
return {
restrict: 'EA',
scope: {},
link: directiveLink,
controller: function ($scope) {
$scope.bar = 'bar';
$scope.myFunction = function () {
$scope.bar = 'foobar2';
};
},
template: "Foo {{bar}}"
};
});
app.directive('mouseDirective', function () {
function directiveLink(scope, element){
element.bind('mouseenter', function(){
scope.$apply(function(){
scope.myFunction();
});
});
element.bind('mouseleave', function(){
scope.$apply(function(){
scope.myOtherFunction();
});
});
}
return {
restrict: 'EA',
link: directiveLink,
controller: function ($scope) {
$scope.bar = 'no';
$scope.myFunction = function () {
$scope.bar = 'yes';
};
$scope.myOtherFunction = function () {
$scope.bar = 'no';
};
},
template: "Mouse Enter: {{bar}}"
};
});
我还在JS Bin链接中包含了一个带有不同控制器的示例。这并没有真正改变任何事情,但它似乎是你问题的重要部分。这是代码块:
var app = angular.module('App', []);
app.controller('myController', function($scope){
$scope.bar = 'foo';
$scope.myFunction = function(){
$scope.bar = 'foobar3';
};
});
app.directive('lastDirective', function () {
function directiveLink(scope){
scope.myFunction();
}
return {
restrict: 'EA',
scope: {},
link: directiveLink,
controller: 'myController',
template: "Foo {{bar}}"
};
});