47

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 ?

1
  • Only tangentially related: if you have a build process, especially one using Grunt, you should check out ngmin. It will make your injectors minification safe and remove the burden of double typing. You'll only need the function($timeout). Commented Sep 25, 2013 at 20:29

1 Answer 1

92

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) {
    ...
});
Sign up to request clarification or add additional context in comments.

2 Comments

I believe with the built in services (anything with a $) you can just put them in the function sig, you don't have to declare them in the dependencies. If you are only using $ services that is.
I think it is done this way for minification purposes docs.angularjs.org/tutorial/step_05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.