始終在範圍 destory 事件上取消註冊 rootScope.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();
});
}