Miguel Moura
Miguel Moura

Reputation: 39464

Factory on Angular ... Is not a constructor when using it

I have the following factory to be able to inject moment.js in my controllers:

angular.module("app").factory("moment", moment);

moment.$inject = ["$window"];

function moment($window) {
  return $window.moment;
}

Then I tried the following:

(function () {

  "use strict";

  angular.module("app").controller("ProjectController", ProjectController);

  ProjectController.$inject = ["projectService", "moment"];

  function ProjectListController(projectService, moment) {
     var date = new moment();
  }
}

But I got the error:

moment is not a constructor

If I change my factory to:

angular
  .module('app')
  .factory('moment', function ($window) {
    return $window.moment;
  });

I don't get an error anymore.

What am I doing wrong with the first syntax?

Upvotes: 1

Views: 574

Answers (1)

danday74
danday74

Reputation: 57116

  angular.module('XRegExp', []).factory('XRegExp', ['$window', function ($window) {
    return $window.XRegExp;
  }]);

  angular.module('lodash', []).factory('_', ['$window', function ($window) {
    return $window._;
  }]);

  angular.module('admin', [
'XRegExp',
'lodash'
  ]);

now inject into your service as usual

Upvotes: 2

Related Questions