AngularJs 广播重复执行太多次 [英] AngularJs broadcast repeating execution too many times

查看:33
本文介绍了AngularJs 广播重复执行太多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个 Angular 控制器中,我有这个:

Inside one of my Angular controllers, I have this:

// controller A
$rootScope.$on("myEventFire", function(event, reload) {
    someAction();
});

在另一个控制器中我有这个:

In another controller I have this:

// controller B
$scope.openList = function(page) {
    $rootScope.$broadcast('myEventFire', 1);
}

现在,这是一个单页应用.当我最初转到控制器 A 并尝试触发此事件时,someAction() 将被执行一次.如果我离开并再次回到控制器 A 并做同样的事情,someAction() 会被执行两次.如果我再做一次,它会发生 3 次,以此类推.我在这里做错了什么?

Now, this is a single-page app. When I go to controller A initially and try triggering this event, someAction() is going to be executed once. If I navigate away and come back again to controller A and do the same thing, someAction() gets executed twice. If I do it again, it happens three times and so on. What am I doing wrong here?

推荐答案

你可以尝试只使用 $scope.$on() 吗?每次创建控制器 A 时,它都会在根范围上添加一个新的侦听器,并且在您离开和返回时不会被破坏.如果您在控制器的本地作用域上执行此操作,则在您离开时监听器应该被移除并且您的作用域被销毁.

Can you try just using $scope.$on()? Every time controller A is created, it is adding a new listener on the root scope, and that doesn't get destroyed when you navigate away and back. If you do it on the controller's local scope, the listener should get removed when you navigate away and your scope gets destroyed.

// controller A
$scope.$on("myEventFire", function(event, reload) {
    someAction();
});

$broadcast 将事件向下发送到所有子作用域,因此它应该在您的本地作用域上被接收.$emit 以另一种方式向根范围向上冒泡.

$broadcast sends the event downward to all child scopes so it should be picked up on your local scope. $emit works the other way bubbling up towards the root scope.

这篇关于AngularJs 广播重复执行太多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆