角度服务未定义

时间:2016-02-10 01:39:35

标签: angularjs angularjs-service

在下面的代码片段中,我收到“ReferenceError:'ShoppingListService'未定义”。我无法看出错误可能是什么,一直撞到它并搜索了一段时间,任何人都有线索?

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。

1 个答案:

答案 0 :(得分: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
}