Peter Joyce
Peter Joyce

Reputation: 43

Angular Service Undefined

In the code snippet below, I'm getting "ReferenceError: 'ShoppingListService' is undefined". I can't see what the error might be, been banging my head against it and searched for a while now, anyone have clues?

var ShoppingListApp = angular.module('ShoppingListApp', [])
ShoppingListApp.factory('ShoppingListService', ['$http', function ($http) {
    var ShoppingListService = {};
    ShoppingListService.getListItems = function () {
        return $http.get('/ShoppingList/GetListItems');
    };
    return ShoppingListService;
}]);

ShoppingListApp.controller('ShoppingListController', function ($scope) {
getItems();
function getItems() {
    ShoppingListService.getListItems() //Error occurs here
    .success(function (shoppingItems) {
        $scope.items = shoppingItems;
        console.log($scope.items);
    })
.[removed for brevity].

The error occurs in the area indicated above. Angular.js version 1.4.9.

Upvotes: 0

Views: 148

Answers (1)

Nix
Nix

Reputation: 58532

In your controller definition ShoppingListController you just have one injectable called $scope you need to add a second one called ShoppingListService.

ShoppingListApp
  .controller('ShoppingListController', ShoppingListController);

ShoppingListController.$inject = ['$scope', 'ShoppingListService']; 
function ShoppingListController($scope, ShoppingListService) { 

    getItems();

    function getItems() {
        ShoppingListService
          .getListItems() //Error occurs here
          .success(onSuccess);  
    }

    function onSuccess(shoppingItems) {
        $scope.items = shoppingItems;
        console.log($scope.items);
    }
    //other code
}

Upvotes: 3

Related Questions