Angularjs Factory is undefined in controller

- 1 answer

Ad

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
        };

            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 target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="CSS/bootstrap.min.css" rel="stylesheet">
 <title>Welcome!</title>
 </head>
 <body>
 <div class="container theme-showcase" role="main" ng-view="">

 </div>

 </body>
Ad

Answer

Ad

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

Ad
source: stackoverflow.com
Ad