我在将ServicesData注入SearchCtrl时遇到问题,并不断收到以下错误消息:Error: [$injector:unpr] Unknown provider: ServicesDataProvider <- ServicesData <- SearchCtrl。这可能是什么原因?

app.js

angular.module('starter', ['ionic', 'jett.ionic.filter.bar', 'starter.controllers'])

  .state('app.playlists', {
    url: '/playlists',
    views: {
      'menuContent': {
        templateUrl: 'templates/playlists.html',
        controller: 'SearchCtrl'
      }
    }
  });
});


controller.js

angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
})

.controller('SearchCtrl', ["$scope", "ServicesData", function($scope, $timeout, ServicesData, $ionicFilterBar) {

    // Get list items

    function getItems () {
      var items = [];
      for (var x = 1; x < 3; x++) {
        items.push({text: 'Item number ' + x});
      }
      $scope.items = items;
    }
    getItems();

    // Ionic filter bar

    var filterBarInstance;

    $scope.visible = true;
    $scope.nulledVisible = false;
    $scope.toggle = function(event) {
        if(event.target.id === 'nulled-search-button' && $scope.nulledVisible === false || event.target.id === 'header-search-button' && $scope.nulledVisible === false) {
          $scope.visible = !$scope.visible;
          $scope.nulledVisible = true;
        }
    };

    $scope.showFilterBar = function () {
      filterBarInstance = $ionicFilterBar.show({
        items: $scope.items,
        update: function (filteredItems, filterText) {
          $scope.items = filteredItems;
          if (filterText) {
            console.log(filterText);
          }
        }
      });
    };

    $scope.refreshItems = function () {
      if (filterBarInstance) {
        filterBarInstance();
        filterBarInstance = null;
      }

      $timeout(function () {
        getItems();
        $scope.$broadcast('scroll.refreshComplete');
      }, 1000);
    };
}]);


services.js

angular.module('starter.services', [])

.service("ServicesData", [function () {
    var servicesData = [
        {
            title: 'Car Repair and Maintenance',
            total: 7,
            id: 1
        }
    ];

    return {
        getAllServices: function () {
            return servicesData;
        }
}])

最佳答案

2件事:
修正您的控制器声明

["$scope", "ServicesData", function($scope, $timeout, $ionicFilterBar)
["$scope", "ServicesData", "$timeout", "$ionicFilterBar", function($scope, ServicesData, $timeout, $ionicFilterBar)


将依赖项添加到服务模块,以便您的控制器将能够访问在start.services模块中声明的内容。

angular.module('starter.controllers', ['starter.services'])

关于javascript - 使用AngularJS难以将服务注入(inject) Controller ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35151645/

10-09 18:22