Search code examples
javascriptangularjsangularjs-factory

AngularJS : Declare factory


following AngularJS in 60 minutes I'm trying to add factory to current code.

I have lineman angular app where angular is declared as follows:

angular.module("app", ["ngResource", "ngRoute"]).run(function($rootScope) {
  // adds some basic utilities to the $rootScope for debugging purposes
  $rootScope.log = function(thing) {
    console.log(thing);
 };
});

I want to add the following code but running into JS syntax issue

.factory('simpleFactory', function () {
  var factory = {};
  var customers = [];
  factory.getCustomers = function () {
    return customers;
  };
  return factory;
}

What's the right syntax to merge these 2 blocks? Also should I do mimic controllers directory to create factory or should I really add to the first block? Thanks


Solution

  • Technically you have already merged a certain block from another:

    angular.module("app", ["ngResource", "ngRoute"])
    
    .run(function($rootScope) {
      // adds some basic utilities to the $rootScope for debugging purposes
      $rootScope.log = function(thing) {
        console.log(thing);
     };
    });
    

    for your chain to continue invoking another method such that the "second block" you are talking about(technically its the third block right now), do not terminate the method invocation then simply remove the terminator ; and append the third block.

    It must look like this:

    angular.module("app", ["ngResource", "ngRoute"]).run(function($rootScope) {
      // adds some basic utilities to the $rootScope for debugging purposes
      $rootScope.log = function(thing) {
        console.log(thing);
     };
    })
    
    .factory('simpleFactory', function () {
      var factory = {};
      var customers = [];
      factory.getCustomers = function () {
        return customers;
      };
      return factory;
    });
    

    Note: Your third method invocation factory() was not closed properly, it lacks the closing parenthesis ) and the terminator symbol ;.