使用工厂在mongoose中插入数据

时间:2014-09-24 10:42:36

标签: angularjs mongoose factory

我正在尝试使用angularjs和node js在mongoose中插入数据。 为此我创建了一个工厂,我正在调用另一个js文件,我已经创建了我的数据库连接。

但是当我试图这样做时,却给了我错误。

这是我的工厂方法:

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

});

以下是我得到的错误:

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 个答案:

答案 0 :(得分:1)

您不能将$ scope注入工厂。服务没有范围。只有控制器。

所以你必须使用这样的东西。

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

然后在你的控制器中。

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