Angularjs的工厂没有工作

时间:2015-05-21 17:17:07

标签: angularjs factory

我试图在angularjs中使用工厂,但它在页面上没有显示任何内容,控制台上没有显示任何错误。

有人能说出我犯的错误吗?

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;

 });

1 个答案:

答案 0 :(得分:1)

我看到的第一个问题是你正在为每个控制器和工厂创建一个新模块。这应该位于同一模块下。为此,例如,应使用简单customerController和工厂app.controller('customerController'....)等实例化app.factory('customersFactory'...)

第二个问题是你试图将$scope注入你无法做到的工厂。查看此更新的plunker http://plnkr.co/edit/0N47C3yFq58H5AyCoh5a?p=preview

我知道能够在一个应用程序中使用多个模块,但是对于您正在做的事情,这是不必要的。如果必须,您已定义var app两次。一旦进入app.js,另一个进入customersFactory.js

customersFactory发送到类似下面的内容,它将起作用

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