Unknown Provider when adding service to controller

穿精又带淫゛_ 提交于 2019-12-06 07:37:14

This error results from the $injector being unable to resolve a required dependency. To fix this, make sure the dependency is defined and spelled correctly. For example, the following code will fail with the same error you received -$injector:unpr, if myService is not defined:

angular.module('myApp', [])
.controller('MyController', ['myService', function (myService) {
  // Do something with myService
}]);

Making sure each dependency is defined will fix the problem, as noted below.

angular.module('myApp', [])
.service('myService', function () { /* ... */ })
.controller('MyController', ['myService', function (myService) {
  // Do something with myService
}]);

So to answer your question, in your case you appear to be missing dependency

angular.module('myApp.controllers', ['ui.bootstrap', 'ngAnimate'])
.controller('HomeCtrl', function($scope, $http, $modal, modalService) {
    $scope.opentheBook = modalService.openMenuModal('partials/Books.html', 'animated zoomIn');
});

To Inject modalService like so:

.controller('HomeCtrl', ['modalService', function($scope, $http, $modal, modalService) {

    }]);

You also need to change up your factory module to angular.module('myApp.services', ['ui.bootstrap']) and use $uibModal since $modal is deprecated.

angular.module('myApp', ['ui.bootstrap'])

.factory('modalService', ['$uibModal', function($uibModal) {

  return {
    openMenuModal: function(templateLink, windowAnimation) {

        var modalObj = $uibModal.open({
            templateUrl: templateLink,
            backdrop: 'static',
            windowClass: windowAnimation,
            controller: function($scope,$modalInstance){
              $scope.ok = function(id){
                //Process OK Button Click
                 $modalInstance.close(); 
              },
               $scope.cancel = function(){
                $modalInstance.dismiss('cancel');
              }
            },
            size: 'md',
            keyboard: true,
            resolve: {
              someData: function () {
                return 'Return some Data';
              }
          }
        });
    }
};
}])

.controller('HomeCtrl', ['$scope','modalService', function($scope, modalService, someData) {
   $scope.dataFromService = someData;
   $scope.opentheBook = function(){
      modalService.openMenuModal('myModalContent.html', 'animated zoomIn');
    };
}]);

UPDATE 1

As mentioned in the comments, do not attempt to inject $scope to your factory. Here is a Plunker I created which lets you open a modal by calling the factory.

http://plnkr.co/edit/G68NVYZlTqrIS0N2TKL4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!