0

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.

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, worked perfectly! Though it works without the ShoppingListController.$inject = ['$scope', 'ShoppingListService']; line. If you don't mind, what's the purpose of that?
It makes your code minification safe. It does the same thing as ShoppingListApp.factory('ShoppingListService', ['$http', function ($http){}]. Its just easier to read. @user1205100

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.