I have the following code:
app.factory('Position', ['$timeout', function() { var position = { latitude: 44, longitude: 26 }; console.log("Timeout started"); $timeout(function() { position.latitude += 15; position.longitude += 15; }, 2000); return position; }]);
And I get $timeout not defined
in Javascript console. Am I not injecting the dependency of the service correctly ?
This '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.
var customTimeout = $timeout(function () { // arbitrary code }, 55); $timeout. cancel(customTimeout); The same applies to “$interval()”. To disable a watch, just call it.
The $timeout service can be used to call another JavaScript function after a given time delay. The $timeout service only schedules a single call to the function. For repeated calling of a function, see $interval later in this text.
setTimeout in order to display an alert message after a timeout of at least 2000 milliseconds. Angular $timeout is a wrapper written for window. setTimeout in form of a try catch block which throws exceptions via $exceptionHandler service. $timeout accepts the function to be delayed, delay time, a boolean to invoke $.
You did not inject $timeout
. It should be as follows.
app.factory('Position', ['$timeout', function($timeout) { ... }]);
Declaration this way ensures that services are correctly identified when your JavaScript code gets minified. For further information on how this helps minification, see A Note on Minification and Declaring AngularJS Modules For Minification
If minification is not in your plans (e.g for quick test), you can simply go with
app.factory('Position', function($timeout) { ... });
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