Angular $rootscope $on Listeners In 'destroyed' Controller Keep Running
Solution 1:
So the question was completely changed so that the context was entirely different, so my previous answer no longer relates to the question really, except that it applies quite the same way.
You can unregister your listener in the same respect as my answer below.
$rootScope.$on()
returns an unregister function.
Therefore, your mainController
can be re-written as:
animateApp.controller('mainController', function($scope, $rootScope, service) {
$scope.pageClass = 'page-home';
var unregister = $rootScope.$on('service.abc', function (newval) {
console.log($scope.$id);
});
$scope.$on('$destroy', unregister);
});
PREVIOUS ANSWER
You should make sure that you unbind your watch when the scope of your controller is destroyed.
When creating a watch, angular returns an unbinding function for the watch you created. This is covered pretty well here.
Create a reference to the watch you create:
var unbinder = $scope.$watch("foo.bar", doStuff);
Watch for your scope's destruction as you were, but call your unbinder
there.
$scope.$on("$destroy", function(){
if(typeof unbinder === "function")
unbinder();
});
Once your unbinder
function is called, your watch will be removed.
Solution 2:
You should add a $destroy
event listener in your controllers:
scope.$on('$destroy', function () {
element.off('blur'); // example
element = null;
});
With this you'll manually make sure that there will be no more active $watchers on inactive controllers.
Post a Comment for "Angular $rootscope $on Listeners In 'destroyed' Controller Keep Running"