admin管理员组

文章数量:1387332

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
}

本文标签: javascriptRemove windowonresize when changing angular controllerStack Overflow