My app.js contains
var app = angular.module('myApp', []).
config(['$routeProvider', function ($routeProvider, $http) {
...
}]);
Service looks like
app.service('MyService', function () {
addNums = function (text) {
return text + "123";
}
});
And in contoller I have
function adminCtrl ($scope, MyService) {
$scope.txt = MyService.addNums("abc");
};
They are all in separate files. The problem is that I’m getting an error
Unknown provider: MyServiceProvider <- MyService
Looks like I’m doing something wrong.
The provider error can occur if you forgot to tell Angular to load your myApp module. E.g., do you have this in your index.html file?:
Your service is missing “this.”:
Fiddle.
There seems to be a lot of confusion in the Angular community about when to use service() vs factory(), and how to properly code them. So, here’s my brief tutorial:
The service() method expects a JavaScript constructor function. Many Angular code examples that use service() contain code that is not a constructor function. Often, they return an object, which kind of defeats the purpose of using service() — more about that below. If an object needs to be created and returned, then factory() can be used instead. Often, a constructor function is all that is needed, and service() can be used.
The quotes below are from different AngularJS Google Group posts:
So when people use service() and its code “return”s an object, it is kind of a waste because of the way JavaScript “new” works: “new” will first create a brand new JavaScript object (then do stuff with prototype, then call the function defined by myService(), etc. — details we don’t really care about here), but because the function defined by myService() returns its own object, “new” does something a bid odd: it throws away the object is just spent time creating and returns the object that the myService() function created, hence the “waste”.
Also, the undocumented naming convention for services seems to be camelCase with first letter lowercased: e.g., myService.