Reputation: 2630
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;
}]);
Upvotes: 1
Views: 262
Reputation: 6306
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.
Upvotes: 2