2016-02-10 56 views
0

在下面的代碼片段中,我得到了「ReferenceError:'ShoppingListService'未定義」。我看不出會發生什麼錯誤,一直抨擊我的頭,並且搜索了一段時間,任何人都有線索?Angular Service Undefined

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]. 

錯誤發生在上面指出的區域。 Angular.js版本1.4.9。

回答

3

在您的控制器定義ShoppingListController中,您只需要一個名爲$scope的注射器,您需要添加第二個稱爲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 
} 
+0

謝謝,工作完美!雖然它沒有ShoppingListController。$ inject = ['$ scope','ShoppingListService'];線。如果你不介意,那是什麼目的? –

+0

它使您的代碼縮小安全。它和'ShoppingListApp.factory('ShoppingListService',['$ http',function($ http){}]''有相同的作用,它更容易閱讀。@ user1205100 – Nix