最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove window.onresize when changing angular controller - Stack Overflow

programmeradmin3浏览0评论

I have a single page app that utilizes ui-router where list page use listController and detail page use detailController.
Detail page has window.onresize event attached while list page doesn't.
The problem is whenever I move from detail page to list page, the onresize event still listen and throw error about the resize target element doesn't exist.

How to remove the window.onresize event listener when I'm changing page?

(function() {
    angular
        .module('app')
        .controller('listController', function() {
            // do things for list page
        })
        .controller('detailController', function() {
            window.onresize = function() {
                // do some resize function
            }
        })
})();

I have a single page app that utilizes ui-router where list page use listController and detail page use detailController.
Detail page has window.onresize event attached while list page doesn't.
The problem is whenever I move from detail page to list page, the onresize event still listen and throw error about the resize target element doesn't exist.

How to remove the window.onresize event listener when I'm changing page?

(function() {
    angular
        .module('app')
        .controller('listController', function() {
            // do things for list page
        })
        .controller('detailController', function() {
            window.onresize = function() {
                // do some resize function
            }
        })
})();
Share Improve this question asked Feb 25, 2016 at 3:17 SkyvorySkyvory 3737 silver badges16 bronze badges 3
  • Maybe simply set window.onresize to null or a new/empty function in the listController? – Aleksandar Bencun Commented Feb 25, 2016 at 3:34
  • It's a bad idea I suppose, since there'll be more pages added along with the controllers. I don't want to add such redundancy to all controllers. – Skyvory Commented Feb 25, 2016 at 4:07
  • Then you can do it on the view unload, but i didn't think of that in time, it's in the answer below, just add the function Rob Glass suggested on the same scope (controller) where you set the window.onresize. – Aleksandar Bencun Commented Feb 25, 2016 at 4:16
Add a ment  | 

1 Answer 1

Reset to default 8

You can reset the onresize function once the route is navigated away from and the controller instance is destroyed.

$scope.$on('$destroy', function() {
   window.onresize = null
}
发布评论

评论列表(0)

  1. 暂无评论