简体   繁体   中英

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

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 ; .

Make sure you chain the factory to your variable. It seems you broke your chain right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM