javascript - Utils class in Angular.js -


i'd create utility class in angular.js can used several controllers.

so far 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 tried use in controller 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 this:

phantomjs 1.9.8 (windows 7 0.0.0) app should dismiss modal failed error: [$injector:undef] provider 'apputils' must return value $get factory method. http://errors.angularjs.org/1.5.0/$injector/undef?p0=invoiceunitsutils

(the real names have been renamed make easier.)

why getting error? not declaring utility module?

the factory in charge of creating service , handing instance you. this, need return 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 vm part because handing service has no view model (the controller in charge of that, service more of business logic expert).

here's more information $get function in angular's providers: https://docs.angularjs.org/guide/providers


Comments