Reputation: 31
I have 2 controllers, both use the same update method to get data:
angular.module('project')
.controller('mainController', function($http, $scope, $timeout, $sce) {
updateData($http, $scope, $timeout, $sce, false);
})
.controller('settingsController', function($http, $scope, $timeout, $sce) {
updateData($http, $scope, $timeout, $sce, true);
})
my updateData
looks like this:
function updateData($http, $scope, $timeout, $sce, settings) {
$timeout(function() {
if (settings) {
getSettings($http, $scope);
}
else {
getDataA($http, $scope);
getDataB($http, $scope);
}
updateData($http, $scope, $timeout, $sce, settings);
}, 1000);
}
Now when refreshing the main page (using mainController
) I always get 'null' messages, because the process did not complete all method calls, and when switching to another site (using settingsController
) it takes ages to load it because all requests from the previous one have to be completed first. How do I directly "kill" all pending updates when refreshing/switching site?
Upvotes: 0
Views: 536
Reputation: 811
you should make a service instead of the function. then you need to inject the service into the controllers.
project.service('updateService', function(){
...some logic here...
});
then inject:
angular.module('project')
.controller('mainController', function($http, $scope, $timeout, $sce, updateService) {
...use "updateService" methods here...
})
and when you write a controller, a small tip, write it like this:
angular.module('project')
.controller('someController', ['$scope', function($scope){
}];
this is important for when you want to make minified version of your code.
Upvotes: 0
Reputation: 23778
This implementation is wrong. I don't think it's a good idea to pass a dependency to an open function and use them. This can create hard-to-detect bugs.
Your updateData
function is a resource killer. It recurs every second without a limitation or control.
There is a design issue in your code. You should reconsider designing it in a standard and effective way.
The answer to your question is that $timeout
returns a promise. You can use the $timeout.cancel method to cancel the timeout.
var timeoutPromise = $timeout(foo(), 1000);
$timeour.cancel(timoeoutPromise);
Upvotes: 3