Supposed I have a controller for a page that is being rendered into an ng-view
.
This controller binds to some events of an external source (such as an application-wide message bus) to update its model. This basically works very easy:
function MyController ($scope) {
$scope.bar = '…';
externalSource.on('foo', function (data) {
$scope.$apply(function () {
$scope.bar = data.bar;
});
});
}
The problem is: How do I unbind the controller from the external source once the view it it is associated with is not longer shown?
Is there something such as a dispose
event or something similar?
Or is my approach completely wrong, and I should deal with something like that somehow else? If so, how?
To execute event unbind when controller's scope is got destroyed use:
$scope.$on('$destroy', function () { /* Unbind code here */ });
See Scope docs for more info
Use $routeChangeStart or $routeChangeSuccess events:
function MyController ($scope) {
$scope.bar = '…';
externalSource.on('foo', function (data) {
$scope.$apply(function () {
$scope.bar = data.bar;
});
});
$scope.$on('$routeChangeStart', function(next, current){
// unregister listener
// externalSource.off ....
});
}
... or $destroy
event:
$scope.$on('$destroy', function(){
// unregister listener
// externalSource.off ....
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With