adi
adi

Reputation: 195

Factory in Angularjs not working

I'm trying to use a factory in angularjs, but it's showing nothing on page, with no errors being displayed on console.

Can anyone point out the mistake I am making?

Here is plnkr link.

var app = angular.module('myApp',[]); 
app.factory('customersFactory',function($scope){

   var customers = [{
    id:1,
    name: 'James',
    city: 'Seattle',
    orderTotal: 9.546,
    joined: '2012-02-05',
    orders:[{
      id:1,
      product:'Shoes',
      total:9.9665
    }]
  }, {
    id:2,
    name: 'Sarah',
    city: 'Dallas',
    orderTotal: 3.653,
    joined: '2010-08-07',
    orders:[{
      id:2,
      product:'Sandal',
      total:8.3465
    }]
  }, {
    id:3,
    name: 'Tom',
    city: 'Troy',
    orderTotal: 8.346,
    joined: '2011-04-09',
    orders:[{
      id:3,
      product:'Sneakers',
      total:6.3427
    }]
  }, {
    id:4,
    name: 'Ling',
    city: 'Columbus',
    orderTotal: 5.549,
    joined: '2014-03-10',
    orders:[{
      id:4,
      product:'belt',
      total:8.9674
    }]
  }];


   var factory={};
   factory.getCustomers = function(){
      return customers;
   };

   factory.getCustomer = function(customerId){
     for (var i = 0, len = customers.length; i < len; i++) {
      if (customers[i].id === parseInt(customerId)) {
          return customers[i];
          }

    }
     return {};
   }

   return factory;

 });

Upvotes: 0

Views: 456

Answers (1)

Ronnie
Ronnie

Reputation: 11198

The first issue I see is you're creating a new module for every controller and factory. This should reside under the same module. To do that, for example, the customerController should be instantiated with a simple app.controller('customerController'....) and the factory app.factory('customersFactory'...) etc

the second issue is you are trying to inject $scope into factory which you cannot do. See this updated plunker http://plnkr.co/edit/0N47C3yFq58H5AyCoh5a?p=preview

I am aware of being able to use multiple modules in a single app, but for what you're doing that is not necessary. If you must, you have defined var app twice. Once in app.js and another in customersFactory.js

Start the customersFactory to something like below and it will work

var fac = angular.module('customersFactory',[]);
fac.factory('customersFactory',function(){
  ...
});

Upvotes: 1

Related Questions