why*_*to8 6 angularjs angularjs-directive angularjs-scope angular-broadcast
我正在开发一个带有角度的单页应用程序,我需要在2个不同的指令之间进行通信,这些指令基本上没有父子关系.
在指令A中,我有2个地方需要从不同的功能广播相同的事件.在指令B中,已经为此写了一个听众.
现在,我观察到第一次调用callFirstFunc及其广播时,将调用一次监听器.在后续调用时,监听器被调用两次,三次等等,它继续增加.
callFirstFunc被执行时调用callSecondFunc,因此对此的监听器也被称为no.在callFirstFunc中广播的监听器的次数.那么,为什么听众只被调用一次,为什么多次?它每次都在循环和增加.
指令A:
app.directive("firstDir", function ($rootScope) {
return {
restrict: 'E',
link: function (scope, element, attrs) {
// some other code
callFirstFunc();
var callFirstFunc = function(){
// some other code
$rootScope.$broadcast("someEvent");
}
callSecondFunc();
var callSecondFunc = function(){
// some other code
$rootScope.$broadcast("someEvent");
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
指令B:
app.directive("secondDir", function ($rootScope) {
return {
restrict: 'E',
link: function (scope, element, attrs) {
// some other code
scope.$on("someEvent", function(){
detectSTuff();
})
function detectStuff(){
// other code
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
我认为您忘记解除事件处理程序的绑定。
你可以这样做 -
var someEventHandle = scope.$on("someEvent", function(){
detectSTuff();
});
scope.$on('$destroy', someEventHandle);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4667 次 |
| 最近记录: |