I'm writing my first AngularJS application. The landing page has two links #/view1
and #/view2
. Every link will call individual controller to render <div ng-view></div>
individually.
The view1Ctrl
will fetch data from server periodically. I can see ajax call in console every X seconds. Now I click #/view2
, the app should use view2Ctrl
. I expect view1Ctrl
should no longer fetch data from the server. But actually it does.
.controller('View1Ctrl', function($scope, $http) {
$scope.update = function() {
$http.get('/api/foo')
.success(function(data) { /* got new data */ })
.error(function(data) { /* error occurred */ })
.finally(function() {
setTimeout($scope.update, 1000);
});
}
$scope.update();
});
I've two questions:
- Is a controller always active after it is initialized.
- What is the best practice to stop any background controllers? My idea is to check the
$location.path()
.
Update 1:
The controller is actually destroyed. But the operation update
will invoke it by itself, so the operation will be called endless.
My current workaround will check whether the current location has been change. So it works. I'm looking for a more elegant way, if it exists.
.controller('View1Ctrl', function($scope, $http) {
$scope.update = function(path) {
$http.get('/api/foo')
.success(function(data) { /* got new data */ })
.error(function(data) { /* error occurred */ })
.finally(function() {
if (path === $location.path()) {
setTimeout($scope.update, 1000, path);
}
});
}
$scope.update($location.path());
});
Update 2:
A better way is to watch destruction and cancel an ongoing timeout promise. Thanks @pankajparkar
.controller('View1Ctrl', function($scope, $http, $timeout) {
var timeoutPromise;
$scope.$on("$destroy", function(){
$timeout.cancel(timeoutPromise);
});
$scope.update = function() {
$http.get('/api/foo')
.success(function(data) { /* got new data */ })
.error(function(data) { /* error occurred */ })
.finally(function() {
timeoutPromise = $timeout($scope.update, 1000);
});
}
$scope.update();
});