JQuery Mobile
JQuery Mobile

Reputation: 6301

Loading Module in AngularJS Service

I'm learning AngularJS. Currently, I'm trying to load a third-party module in my service. Specifically, I'm trying to load angular-moment. My service is defined like this:

myApp.factory('myService', ['angularMoment', function(angularMoment) {
  return {
    getLocale: function() {
      return angularMoment.locale();
    }
  }
}]);

If I replace return angularMoment.locale() with return 'someLocale'; my code runs. However, as soon as I reference angularMoment, I get errors. I know it has something to do with the fact that I'm not loading the module correctly. However, I do not know what I'm doing wrong. I just see this error when I run my unit tests:

Error: [$injector:unpr] http://errors.angularjs.org/1.2.22/$injector/unpr?p0=angularMomentProvider%20%3C-%20angularMoment%20%3C-myService (line 36) (1)

What am I doing wrong?

Upvotes: 5

Views: 820

Answers (4)

Arvid Villén
Arvid Villén

Reputation: 1

This worked for me:

var app = angular.module('myApp', ['angularMoment']);

app.controller('myCtrl', function($scope, $log, moment) {
      var now = moment();
      $log.info(now.format("dddd, MMMM Do YYYY, h:mm:ss a"));
});

Upvotes: 0

bhantol
bhantol

Reputation: 9616

Try 'moment' instead of angularMoment in the service/factor injector. This will give you the object from MomentJS

myApp.factory('myService', ['moment', function(moment) {
  return {
    getLocale: function() {
      return moment.locale();
    }
  }
}]);

Upvotes: 2

Timothy
Timothy

Reputation: 1160

This is going to sound basic, but you are referencing the .js files in your html code, right?

Upvotes: 0

Jack A.
Jack A.

Reputation: 4443

You need to reference the angularMoment module when declaring your module. Otherwise it won't get loaded. That is what causes the $injector:unpr error. So you need something like this:

var myApp = angular.module("myApp", ["angularMoment"]);

Upvotes: 0

Related Questions