2014-12-07 4 views
0

Я хочу начать с того, что я очень новичок в AngularJS, поэтому любая помощь будет оценена!AngularJS - Factory.function (...) не определено

Я пытаюсь собрать некоторые данные JSON из URL-адреса в заводской функции, а затем вернуть данные контроллеру, но он выдает сообщение об ошибке, заявляя, что функция не существует. Я слежу вместе с учебной серией по Udemy, но данные, которые я собираю, поступают из другого источника, поэтому ответа нет в видео.

Код:

angular.module('MainModule', ['ngRoute']); 
angular.module('MainModule').config(function($routeProvider){ 
    $routeProvider.when('/', { 
     templateUrl: '/templates/index.html' 
    }); 
    $routeProvider.when('/item/:id', { 
     templateUrl: '/templates/item.html', 
    }); 
}); 
angular.module('MainModule').controller('ItemsController', function($scope, ItemsFactory, MainSettings){ 
    ItemsFactory.getItems().then(function(response){ 
     $scope.items = response; 
    }); 
    $scope.settings = MainSettings; 
}); 
angular.module('MainModule').controller('ItemController', function($scope, $routeParams, ItemsFactory, MainSettings){ 
    $scope.item = ItemsFactory.getItem($routeParams.id); 
    $scope.settings = MainSettings; 
}); 
angular.module('MainModule').factory('ItemsFactory', function($http, $log){ 
    var factory = {}; 
    var items = false; 
    factory.getItems = function(){ 
     $http.get('/index.php').success(function(response){ 
      items = response.items; 
      return items; 
     }); 
    }; 
    factory.getItem = function(item){ 
     var i = 0; 
     while (i < items.length) { 
      if (items[i].id == item) { 
       return items[i]; 
      } 
      i++; 
     } 
     return false; 
    }; 
    return factory; 
}); 
angular.module('MainModule').constant('MainSettings', { 
    title: 'Simple RSS Reader', 
    version: '1.0' 
}); 

Ошибка:

Error: ItemsFactory.getItems(...) is undefined 
@http://192.168.1.234:1000/js/angular-module.js:11:2 
[email protected]://192.168.1.234:1000/js/angular.js:3965:14 
[email protected]://192.168.1.234:1000/js/angular.js:3976:23 
$ControllerProvider/this.$get</<@http://192.168.1.234:1000/js/angular.js:7307:18 
nodeLinkFn/<@http://192.168.1.234:1000/js/angular.js:6696:34 
[email protected]://192.168.1.234:1000/js/angular.js:332:11 
[email protected]://192.168.1.234:1000/js/angular.js:6683:11 
[email protected]://192.168.1.234:1000/js/angular.js:6131:13 
[email protected]://192.168.1.234:1000/js/angular.js:6027:30 
ngViewFillContentFactory/<[email protected]://192.168.1.234:1000/js/angular-route.js:915:7 
[email protected]://192.168.1.234:1000/js/angular.js:6737:13 
[email protected]://192.168.1.234:1000/js/angular.js:6131:13 
[email protected]://192.168.1.234:1000/js/angular.js:6027:30 
createBoundTranscludeFn/[email protected]://192.168.1.234:1000/js/angular.js:6151:21 
[email protected]://192.168.1.234:1000/js/angular.js:6758:18 
[email protected]://192.168.1.234:1000/js/angular-route.js:865:25 
$RootScopeProvider/this.$get</[email protected]://192.168.1.234:1000/js/angular.js:13070:15 
updateRoute/<@http://192.168.1.234:1000/js/angular-route.js:547:15 
qFactory/defer/deferred.promise.then/[email protected]://192.168.1.234:1000/js/angular.js:11659:31 
qFactory/defer/deferred.promise.then/[email protected]://192.168.1.234:1000/js/angular.js:11659:31 
qFactory/ref/<.then/<@http://192.168.1.234:1000/js/angular.js:11745:26 
$RootScopeProvider/this.$get</[email protected]://192.168.1.234:1000/js/angular.js:12788:16 
$RootScopeProvider/this.$get</[email protected]://192.168.1.234:1000/js/angular.js:12600:15 
$RootScopeProvider/this.$get</[email protected]://192.168.1.234:1000/js/angular.js:12892:13 
[email protected]://192.168.1.234:1000/js/angular.js:8427:34 
[email protected]://192.168.1.234:1000/js/angular.js:8641:7 
createHttpBackend/</[email protected]://192.168.1.234:1000/js/angular.js:8580:1 

<div class="ng-scope" ng-view=""> 

Заранее спасибо, Мэтт!

+1

Ваша функция 'factory.getItems' ничего не возвращает, вам нужно просто вернуть свой _ $ http_ как' factory.getItems = function() { return $ http.get ('/ index.php'). (функция (ответ) { items = response.items; возвратные элементы; }); }; ' – Grundy

ответ

0

Моя проблема была похожа на это, и я решил его, вводя свой завод, как так -

angular.module('MainModule').controller('ItemsController', ['ItemsFactory', function($scope, ItemsFactory, MainSettings){ 
    ItemsFactory.getItems() 
    .success(function(response) {..}) 
    .error(function(response) {..}) 
    .then(function(response){ 
     $scope.items = response; 
    }); 
    $scope.settings = MainSettings; 
}]); 

Вы бы в конечном итоге сделать это, если вы решили использовать библиотеку минификации или RequireJS. Дополнительная информация here в официальной документации.

0

Оба исправления, отдельно и вместе удаляют ошибку, но данные по-прежнему не возвращаются. Означает ли порядок, что инъекции указаны в контроллере, имеет какое-то значение для того, как они работают?

+0

вы можете обновить свое сообщение, вместо этого добавляя ответ, который не отвечает. также, что вы имеете в виду, но данные еще не возвращены? – Grundy

+0

Ошибка была удалена, но данные JSON, которые я ожидаю вернуть, недоступны в контроллере. –

+0

обновить сообщение с изменениями. вы пытаетесь отладить его? – Grundy

Смежные вопросы