简体   繁体   中英

Angularjs Factory is undefined in controller

I am new in angular js, now I am trying to use factory to make code clearer. But now I am getting the following error:

$injector:unpr(Unknown provider).

I stuck here and cant find where is the problem. Service and this controller were in different files actually, then I tried to put them together, but still it doesnt work. I will be very glad if you will help me to find out my problem.

var app = angular.module('myApp', ['ngRoute']);
app.factory('AuthenticationService', ['$scope', '$location', function($scope, $location){

var currentUser;

return {
    login: function(username, password){
        var endPoint = "http://localhost:8080/RestServer/main/just/Authorize";
        var jsonData = {
            username: username,
            password: password
        };
        var jsonString = JSON.stringify(jsonData);

        $http.post(endPoint, jsonString,{headers: {'Content-Type': 'application/json'}}).success(function (data,status, headers ){

            if(data.access == "ok")
            {
                $location.path("learning");
            }
            else
            {
                $location.path("error");
            }

        });
    },
    logout: function(){},
    isLoggedIn: function(){},
    curUser: function(){return currentUser}
};
}
]);
app.controller('loginController',['$scope', 'AuthenticationService',      function($scope, AuthenticationService)
{
    $scope.login = function()
    {
        AuthenticationService.login($scope.username, $scope.password);
    }
}]);

Here is html:

 <html data-ng-app="myApp">
 <head>
<script src="https://code.angularjs.org/1.5.0-rc.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular-route.min.js"></script>
<script src="Scripts/app.js"></script>
<script src="Scripts/services.js"></script>
<script src="Scripts/controllers.js"></script>
 <link href="CSS/bootstrap.min.css" rel="stylesheet">
 <title>Welcome!</title>
 </head>
 <body>
 <div class="container theme-showcase" role="main" ng-view="">

 </div>

 </body>

Just remove $scope from your factory, You don't typically use $scope inside a factory, service or provider,also add $http as a dependency since you are making a $http call

app.factory('AuthenticationService', [ '$location','$http', function( $location,$http){
}

Here is the working Application

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