2

對不起,如果這是一個簡單的問題。我是新人,可能不理解正確的事情來尋找答案。AngularJS:無法將工廠連接到控制器

我基本上遵循了這一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' } 
    ];   
}]); 
+1

改變你的工廠在2002年底:'{回報getPeople:函數(){返回的人;}};' – calebboyd

+1

只要將 '回廠;'到你工廠的盡頭,你應該是金的。 –

回答

0

從本質上講,你只是從你的「工廠」對象缺少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(); 
}); 

所以現在我們有一個描述性的工廠,返回一個對象的人,其中之一稱爲查詢。我們稍後可以更新這個查詢函數來讀取參數,發起AJAX調用並做一些複雜的事情。但一次只能一步:)

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();   
}]);