$locationChangeSuccess triggers four times

对着背影说爱祢 提交于 2019-12-04 15:55:19

After running into this myself, the problem lies in the fact you are using the root scope to bind the locationChangeSuccess event from within a directive that is either encountered multiple times on a single page, or encountered multiple times as you revisit the page:

$rootScope.$on('$locationChangeSuccess', function(event, url, oldUrl, state, oldState){

Since you are binding to the rootScope, and the rootScope does not go out of scope, the event binding is not cleaned up for you.

Inside your link function, you should add a listener for the element $destroy, as well as capture the return value from the original bind, so you can later unbind it.

First: capture return value:

var unbindChangeSuccess = $rootScope.$on('$locationChangeSuccess' ...

Next, unbind that value in your destroy method:

element.on('$destroy', function() {
    unbindChangeSuccess();
});

That should solve the multiple calls to your locationChangeSuccess! :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!