1

I'd like to create an utility class in Angular.js that can be used by several controllers.

So far I created this:

'use strict';
angular
  .module('App')
  .factory('AppUtils', AppUtils);

function AppUtils() {
  var vm = this;

  vm.getPersonOf = getPersonOf;

  function getPersonOf(personId, allPersons) {
    var person = {};
    person.personId = {personId: personId};
    allPersons.forEach(function(p) {
      if (p.personId === personId) {
        person = p;
      }
    });
    return person;
  }

}

And I tried to use it in a controller like this:

'use strict';
angular
  .module('App')
  .controller('AppController', AppController);

function AppController(personId, allPersons, AppUtils) {

var vm = this;
vm.personId = personId;

vm.person = AppUtils.getPersonOf(vm.personId, allPersons);

...
}

But I get this:

PhantomJS 1.9.8 (Windows 7 0.0.0) App should dismiss modal FAILED Error: [$injector:undef] Provider 'AppUtils' must return a value from $get factory method. http://errors.angularjs.org/1.5.0/$injector/undef?p0=InvoiceUnitsUtils

(The real names have been renamed to make it easier.)

Why am I getting that error? Am I not declaring properly the Utility module?

2
  • That's not how one uses factory. What you're doing should be a service Commented Aug 1, 2016 at 13:29
  • You just need to return vm; at the end of factory. Commented Aug 1, 2016 at 13:36

1 Answer 1

1

The factory is in charge of creating a service and handing its instance to you. To do this, you need to return your utility class:

function AppUtils() {

     return { 
      getPersonOf: getPersonOf
     // pass other utility functions...
    }

    function getPersonOf(personId, allPersons) {
        var person = {};
        person.personId = {personId: personId};
        allPersons.forEach(function(p) {
            if (p.personId === personId) {
                person = p;
            }
        });
        return person;
     }
  }

I removed the vm part because we are handing a service which usually has no view model (the controller is in charge of that, service is more of a business logic expert).

Here's some more information about the $get function in Angular's providers: https://docs.angularjs.org/guide/providers

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.