Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$timeout not defined error in AngularJS app

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 ?

like image 650
Radu Stoenescu Avatar asked Sep 25 '13 15:09

Radu Stoenescu


People also ask

What is $timeout in AngularJS?

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.

How do you reset a $timeout and disable a watch ()?

var customTimeout = $timeout(function () { // arbitrary code }, 55); $timeout. cancel(customTimeout); The same applies to “$interval()”. To disable a watch, just call it.

What is the function of the $timeout service?

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.

What is the difference between $timeout and setTimeout?

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 $.


1 Answers

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) {     ... }); 
like image 176
kubuntu Avatar answered Oct 01 '22 02:10

kubuntu