Insert data in mongoose using a factory

2019-03-02 12:16发布

问题:

I am trying to insert data in mongoose using angularjs and node js. For this i have created a factory where i am calling another js file where i have created my database connection.

But when i tried to do this, it is giving me error.

Here is my factory method:

'use strict'
test.factory('registrationservice', function($http, $scope){
    console.log('aa');
    $scope.newregister = function(user, $scope) {

        var newUser = new user({
            username: $scope.uName,
            firstname: $scope.fName,
            lastname: $scope.lName,
            email:$scope.mail,
            password: $scope.newpwd

        });

        console.dir(newUser);

        var $promise = $http.post('data/registration.js', newUser);
        $promise.then(function(msg){
            if(msg.data == 'success') console.log('success login')
            else
                console.log('login failed');
        });
    };

});

and below is the error i am getting:

Error: [$injector:unpr] http://errors.angularjs.org/1.2.7/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20registrationservice
    at Error (native)

回答1:

You cannot inject $scope to factory. Services do not have scopes. Only Controllers.

So you have to use something like this.

test.factory('registrationservice', function($http){
    var factory = {};
    // if user is another service you have to inject it in factory defenotion function
    // and delete from here.
    facotry.newregister = function(user, $scope) {

        var newUser = new user({
            username: $scope.uName,
            firstname: $scope.fName,
            lastname: $scope.lName,
            email:$scope.mail,
            password: $scope.newpwd

        });

        return $http.post('data/registration.js', newUser);
    }
    return factory;
});

And then in your controller.

test.controller('registrationCtrl', function($scope, $log, registrationservice){ 
    registrationservice.newregister(user, $scope).success(function(msg){
        $log.info(msg.data);
    })
});