Search code examples
javascriptangularjsonresize

Remove window.onresize when changing angular controller


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
            }
        })
})();

Solution

  • 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
    }