简体   繁体   中英

Injecting factory to controller doesn't work in angular 1.6

I'm going crazy with this one.

I have 3 files: app.js, app.services.provider.js, admin.js

In app.js I define my module:

(function() {

    angular.module('myApp', ['ngRoute']).config(function ($routeProvider) {
         $routeProvider 
        .when("/admin", {
            templateUrl : "Admin.htm",
            controller: "AdminController"
        }).otherwise( {redirectTo: '/'} ) ;
    })

})();

Now in app.services.provider.js I define a factory:

(function() {

 angular.module("myApp").factory('appServicesProvider',function($scope, $http ) {
      function someFunction(){

      }

      return{someFunction:someFunction}

    });

})();

And in admin.js I have my controller:

(function() {

angular.module("myApp")
.controller("AdminController",function($scope, $http, appServicesProvider) {

});

})();

Now I believe I include the JS in the right order in my index.html:

<script src="js/app.js"></script>
<script src="js/app.services.provider.js"></script>
<script src="js/admin.js"></script>

Yet when I try to run the code I get the exception:

angular.min.js:122 Error: [$injector:unpr] http://errors.angularjs.org/1.6.1/$injector/unpr?p0=<ng-view class="ng-scope">copeProvider%20%3C-%20%24scope%20%3C-%20appServicesProvide

And I can't seem to understand when goes wrong

I tried several things:

  • I tried including the scripts in both head and at the end of body tag
  • I tried removing the (function() {})();
  • I tried referencing my module in a var, ie var app = angular.module(...) and using the variable across the files
  • I tried injecting the "AppServices" like this: angular.module("myApp") .controller("AdminController",["$scope","$http","appServicesProvider",function($scope, $http, appServicesProvider) {...

And it still shows that damn error.

Anyone has an idea what could have went wrong?

Thanks for your help, Eric

The error is because you're trying to inject $scope into your service. There is no $scope for services.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM