始終取消註冊在當前範圍以外的其他範圍上註冊的偵聽器

你必須始終取消註冊當前範圍之外的範圍,如下所示:

//always deregister these
$rootScope.$on(...);
$scope.$parent.$on(...);

你不必在當前範圍內取消註冊列表,因為 angular 會處理它:

//no need to deregister this
$scope.$on(...);

如果導航到另一個控制器,$rootScope.$on 偵聽器將保留在記憶體中。如果控制器超出範圍,這將產生記憶體洩漏。

angular.module('app').controller('badExampleController', badExample);
badExample.$inject = ['$scope', '$rootScope'];

function badExample($scope, $rootScope) {
    $rootScope.$on('post:created', function postCreated(event, data) {});
}

angular.module('app').controller('goodExampleController', goodExample);
goodExample.$inject = ['$scope', '$rootScope'];

function goodExample($scope, $rootScope) {
    var deregister = $rootScope.$on('post:created', function postCreated(event, data) {});

    $scope.$on('$destroy', function destroyScope() {
        deregister();
    });
}