Search code examples
javascriptangularjsangularjs-serviceangularjs-controllerangularjs-factory

PassFactory.setNewPass is not a function, factory function not a function


Can't seem to get this factory to work properly. I'm trying to do the $http requests from a factory. But I'm getting this error of:

TypeError: PassFactory.setNewPass is not a function

Below is the code:

Factory

   (function () {
        angular
            .module("myApp")
            .factory('PassFactory', ['$http', function ($http) {
    /*
                var passFactory = {};
                passFactory.setNewPass = function (newpass, user) {
                    return $http.post('/password/' + newpass, user, function (response) {
                    });
                };
    */
                return {
                    setNewPass: function (newpass, user) {
                        return $http.post('/password/' + newpass, user, function (response) {
                        });
                    }
                };
            }])
    })();



Controller

 (function () {
        angular
            .module("myApp")
            .controller('PCtrl', ['$scope', '$location', '$rootScope', 'PassFactory', setHome]);

        function setHome($scope, $location, PassFactory) {
            $scope.login = function (user) {
                if (user.newpassword == user.newpasswordconfirm) {


                    PassFactory.setNewPass(user.newpassword, user).then(function (response) {
                        $location.path("/");
                    });


                }
            };
        }
    })();

Solution

  • You have missed $rootScope in controller factory function. Always make sure the the order in dependency have been injected inside DI array, in same sequence you should ask for their instance inside its factory function.

    angular
     .module("myApp")
     .controller('PCtrl', ['$scope', '$location', '$rootScope', 'PassFactory', setHome]);
    
    //added $rootScope in 3rd place
    function setHome($scope, $location, $rootScope, PassFactory) {