1

I'm trying to define a service with methods that I can call from a module in AngularJS. This is my first attempt at using AngularJS. Maybe this isn't a good way to do it, but I thought that I could put some helper methods into a service that could be then reusable.

But I'm finding that the UrlHelperService isn't available from the module.

I've tried to simplify and extract just the skeleton of the three files being used:

app.js

angular.module('myApp', ['ngRoute', 'myMod', 'UrlHelperService']);

urls.js

var serv = angular.module('UrlHelperService', []);
serv.service( "UrlHelperService",
              function aaMethod( ) {
                 this.urlHelp = function( url, aa ) {
                     return url;
                 }
               }
            );

module.js

var module = angular.module( "myMod", [] );
module.factory(
    "myMod",
    [ "$http", "$q", "UrlHelperService",
                function myModFactory( $http, $q, UrlHelperService) {
                    // UrlHelperService isn't available here.  Why?
                    return;
                }]);
1
  • 1
    You have only injected it into another module named myApp. You also have to inject UrlHelperService into the module var module = angular.module("myMod", ['UrlHelperService']); if you'd like to use it there. Commented May 20, 2014 at 0:56

1 Answer 1

2

Well, if you want to use UrlHelperService with myMod you need to declare it as a dependency in myMod (as you do in myApp).

var module = angular.module( "myMod", [
    "UrlHelperService"
]);
module.factory(
    "myMod", [
        "$http",
        "$q",
        "UrlHelperService",
        function myModFactory( $http, $q, UrlHelperService) {
            // UrlHelperService isn't available here.  Why?
            return;
        }
    ]);

But it could possibly be even simpler. You are creating a myMod module and a myMod service (.factory is similar to .service), why?

Anyway, you're absolutely right to putting these helper function in a service you can reuse. It doesn't have top be on its own module though. Perhaps a simpler approach would be good enough. For example:

angular
    .module('myApp', [
        'ngRoute'
    ])
    .factory('UrlHelperService', [
        function UrlHelperService() {
            return {
                urlHelp: function(url, aa) {
                    return url;
                }
            };
        }
    ]);

Here you have your app (its own module) and a service available to everyone else inside myApp. Sometime a separate module for some services etc is better, sometimes a service inside your main module is good enough.

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

Comments

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.