AngularJS:无法将工厂连接到控制器

时间:2014-02-27 01:31:18

标签: javascript angularjs angularjs-service angularjs-controller angularjs-factory

如果这是一个简单的问题,我很抱歉。我是新手,可能不理解寻找答案的正确方法。

我基本上遵循了这个angularJS教程http://www.youtube.com/watch?v=i9MHigUZKEM

除了设置连接到我的控制器的工厂外,我已经完成了所有这些工作。

以下是工厂的代码:

    demoApp.factory('simpleFactory', function(){
    var people = [
          { name: 'Will', age: '30' },
          { name:'Jack', age:'26' },
          { name: 'Nadine', age: '21' },
          { name:'Zach', age:'28' }
        ];

  var factory = {};
  factory.getPeople = function() {
    return people;
  };
});

这是控制器:

    demoApp.controller('FirstCtrl', ['$scope', 'simpleFactory', function ($scope, simpleFactory) {

    $scope.people = simpleFactory.getPeople();        
    }]);

只是HTML中的一个简单重复:

Name:
   <input type="text" ng-model="filter.name"> {{ nameText }}
   <ul>
      <li ng-repeat="person in people | filter:filter.name | orderBy: 'name'">{{ person.name }}- {{ person.age }}</li>
   </ul>

我得到的错误是“TypeError:无法在javascript控制台中调用未定义的方法'getPeople'。

注意:这在控制器中我可以正常工作,我将数据对象硬编码为:

    demoApp.controller('FirstCtrl', ['$scope', 'simpleFactory', function ($scope, simpleFactory) {

    $scope.people = [
      { name: 'Will', age: '30' },
      { name:'Jack', age:'26' },
      { name: 'Nadine', age: '21' },
      { name:'Zach', age:'28' }
    ];        
 }]);

2 个答案:

答案 0 :(得分:2)

您的服务稍有变化;

  demoApp.factory('simpleFactory', function(){
  var people = [
        { name: 'Will', age: '30' },
        { name:'Jack', age:'26' },
        { name: 'Nadine', age: '21' },
        { name:'Zach', age:'28' }
  ];

  return {
    getPeople: function() {
     return people;
    };
  }

});

在您的控制器中

demoApp.controller('FirstCtrl', ['$scope', 'simpleFactory', function ($scope, simpleFactory) {

$scope.people = simpleFactory.getPeople();        
}]);

答案 1 :(得分:0)

基本上你只是错过了'factory'对象的return语句,但是如果你做一点重命名以避免混淆可能会更清楚。

示例,改编自AngularJS书:

demoApp.factory('People', function(){ // Renamed factory to be more descriptive
  var people = {}; // Renamed 'factory' to 'people', as an object we can prototype more functions later

  people.query = function() { // called query, but could be getPeople
    return [ // just return a static array for now
      { name: 'Will', age: '30' },
      { name:'Jack', age:'26' },
      { name: 'Nadine', age: '21' },
      { name:'Zach', age:'28' }
    ];
  }

  return people;
});

现在您的控制器可以在以下位置提取此信息:

demoApp.controller('FirstCtrl', ['$scope', 'People', function ($scope, People) { // dependency injection
  $scope.people = People.query();
});

所以现在我们为People提供了一个返回对象的描述性工厂,其中一个被称为查询。我们以后可以更新这个查询函数来读取参数,触发AJAX调用并执行一些复杂的操作。但是一步一步:)