1

I am trying to redefine angular.module multiple times one is for controller and one is for service etc. TestService is a factory which is defined in test.js and i want to use it in current html page.

HTML

<script src="test.js"></script>

<script>
var app = angular.module("myapp", ['TestService']).controller(
    "MyController", function($scope, $cookies,TestService ) {

<script>

Now i have another javascript page where i am trying to write a service.

test.js

angular.module("myapp").factory('TestService', function() {
     return {
        sayHello: function(){
            return "Factory says hi;
        }

    } 
});

i am getting the error 'TestService' is not available!

1 Answer 1

1

Your HTML should look like this:

<script>
    var app = angular.module("myapp", [])
    .controller("MyController", function($scope, $cookies, TestService) {
        // ...
    });
</script>

<script src="test.js"></script>

Meaning that you first need to define module (angular.module("myapp", [])), then register service on it.

Sign up to request clarification or add additional context in comments.

2 Comments

yes, but is it not required to inject the service inside the square bracket here? i.e angular.module("myapp", ['TestService']) vs angular.module("myapp", [])
When you create module you don't inject anything, those are dependent modules in brackets, not services. So you could for example create module Test, put your service there and then use Test as a dependency for main module. angular.module('Test', []).factory('TestService', function() { ... }); angular.module('myapp', ['Test']).controller('MyController', function() { ... }).

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.