Angular:如何将$ scope变量传递给Node.js服务器。 [英] Angular: how to pass $scope variables into the Node.js server.

查看:120
本文介绍了Angular:如何将$ scope变量传递给Node.js服务器。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有这个表单:

 < form ng-submit =submit()ng-controller = formCtrl > 
< input ng-model =formData.stickietype =textid =sticky_content/>
< button type =submitid =add_stickyvalue =add a new stickie!> new sticky< / button>
< / form>

此模型控制:



<$ p $ ($ scope,$ http){

$ scope.submit = function(){
$ http.post ('/ api / stickies',$ scope.formData)
****以某种方式将数据分配给下面的函数可用的东西******

})
.error(function(data){
console.log('Error:'+ data);
});
};
});

我想能够使用这里发布的数据:

  app.post('/ api / stickies',function(req,res){
var test = formData.stickie; //返回undefined对于粘贴和formData.stickie
db.run(INSERT INTO stickies(data)VALUES(?),[test]);
});

所以总结来说,我试图将$ scope.formData变量传递到我的server.js文件所以它可以在我的app.post函数中使用(并插入到数据库中)



编辑:根据下面给出的答案更新代码:当前得到`ReferenceError: formData没有定义,当我提交表单。

解决方案

当您使用 ng-model 时,组件到范围使用某些名称。这意味着

 < input ng-model =stickie_texttype =textid =sticky_content/> 

将带给您一个 $ scope.stickie_text 您的组件的当前值在您的'formCtrl'控制器中。记住它是一个双向绑定:如果你改变了这个变量,你也改变了表单控件的值。



我们来重构这个:

 < form ng-submit =submit()ng-controller =formCtrl> 
< input ng-model =stickie_texttype =textid =sticky_content/>
< button type =submitid =add_stickyvalue =add a new stickie!> new sticky< / button>
< / form>

此表单只有一个字段: stickie_text 。另一个是按钮。
到目前为止,您的表单有一个字段,在指定名称范围内存储和读取数据( $ scope.stickie_text



当您提交表单时,您的 $ scope.submit 函数正在被调用:

  $ scope.submit = function(){
$ http
.post('/ api / stickies',{什么:to,put:here})
.success(function(data){
//在这里做什么
})
.error(function(data){
console.log('Error:'+ data);
});
};

所以这是你的处理程序,最大的问题是:




  • 在这里做什么?

  • 如何发布数据?

  • 如何处理一旦我发布了相同的数据?



注意我改变了你的处理程序 - 放置一个注释并替换数据对象。 p>

POST数据必须与服务器端匹配。所以如果你的stickie必须通过名称 stickie (这样一来 req.body.stickie 表达式存在于服务器端),您必须编写的数据是这样的: {stickie:$ scope.stickie_text} 。这是因为 stickie_text 是您在视图中使用的名称,因此它是该字段将读取和写入的范围var的名称。记住在您的应用程序中安装 body解析器中间件。



我不记得很多nodej,但如果我可以这样做:

  app.post('/ api / stickies',function(req,res) 
var test = req.body.stickie;
db.run(INSERT INTO stickies(data)VALUES(?),[test]);
});

如果您从客户端使用相同的数据库,将会执行 。您还应该在响应( res )对象中写入某些内容,但这取决于您和nodejs以及您首选的方式(例如 res.write )。



所以,我们将坚持一样的例子:

  $ scope.submit = function(){
$ http
.post('/ api / stickies',{stickie:$ scope.stickie_text})
.success(function(data){
//在这里做什么?这取决于你和你从服务器写的数据
})
.error(function(data){
console.log('Error:'+ data);
});
};

测试并检查您的数据库。



编辑 - 由@Kousha建议 - 为您的表单数据使用一个事实上的命名空间(如您之前提到的 formData - 记住这是一个示例,您可以使用任何您想要的名称)。它的工作原理如下:


  1. ng-model ,所以同一个对象持有表单数据。既然你只有一个字段,那就足够了:

      ng-model =formData.stickie

    故意改变变量名称以匹配nodejs服务器中等待的名称。不要忘记这一点,因为我将直接使用对象作为数据。


  2. 最终值 $ scope.formData 将是 {stickie:whatEverIsInTheputField} 。如果我使用 ng-model =formDta.foo添加另一个字段作为绑定,最终值 $ scope.formData 将是 {stickie:whatEverIsInTheInputField,foo:otherFieldValue}


  3. 我使用 $ scope.formData 直接在http请求中:

      $ scope.submit = function(){
    $ http
    .post('/ api / stickies',$ scope.formData)
    .success(function(data){
    //该做什么
    .error(function(data){
    console.log('Error:'+ data);
    });
    };


  4. 虽然 formData 不存在在 $ scope 中,绑定在创建 stickie 之前隐式创建它。



right now I have this form:

<form ng-submit = "submit()"ng-controller = "formCtrl">
                <input ng-model="formData.stickie" type="text" id="sticky_content" />
                <button type="submit" id="add_sticky" value="add a new stickie!">new sticky</button> 
        </form>

controlled by this model:

app.controller('formCtrl',function($scope,$http){

        $scope.submit = function() {
                $http.post('/api/stickies', $scope.formData)
                                **** somehow assign data to something useable by the function below???******

                        })
                        .error(function(data){
                                console.log('Error: ' + data);
                        });
        };
});

and I want to be able to use the posted data in here:

app.post('/api/stickies',function(req,res){
        var test = formData.stickie;    //returns undefined for sticky and for formData.stickie
        db.run("INSERT INTO stickies (data) VALUES (?)", [ test ]);
});

so in summary, I am trying to pass the $scope.formData variable into my server.js file so that it can be used in my app.post function (and inserted into the db)

Edit: updated code in accordance with answer given below: currently getting `ReferenceError: formData is not Defined, when I submit the form.

解决方案

When you use ng-model it is to bind your form components to the scope using certain name. this means that

<input ng-model="stickie_text" type="text" id="sticky_content" />

will bring you a $scope.stickie_text with the current value of your component in your 'formCtrl' controller. Remember it's a bidirectional binding: if you alter that variable, you also alter the value in the form control.

Let's refactor this:

<form ng-submit="submit()" ng-controller="formCtrl">
    <input ng-model="stickie_text" type="text" id="sticky_content" />
    <button type="submit" id="add_sticky" value="add a new stickie!">new sticky</button> 
</form>

This form has only one field: stickie_text. The other one is a button. So far, your form has one field, which stores and reads data in the scope in the specified name ($scope.stickie_text).

When you submit the form, your $scope.submit function is being invoked:

$scope.submit = function() {
    $http
        .post('/api/stickies', {what: to, put: here})
        .success(function(data){
            //what to do here
        })
        .error(function(data){
            console.log('Error: ' + data);
        });
};

So this is your handler and the big question is:

  • what to do here?
  • How do I post the data?
  • How do I handle the same data once I post it?

Notice I changed your handler a bit - placing a comment and replacing the data object.

The POST data must match the server-side. So if your stickie must fly through the network under the name stickie (in this way, a req.body.stickie expression exists on the server-side), the data you must compose is this: {stickie: $scope.stickie_text}. This is because stickie_text is the name you used in the view, and so it's the name of the scope var where such field will read and write from. Remember to install the body parser middleware in your application.

I don't remember much of nodejs, but if I'm right, perhaps doing:

app.post('/api/stickies',function(req,res){
    var test = req.body.stickie;
    db.run("INSERT INTO stickies (data) VALUES (?)", [ test ]);
});

Will do it AS LONG AS YOU USE THE SAME DATA KEYS FROM THE CLIENT. You should also write something in the response (res) object, but that's up to you and nodejs, and your preferred way (e.g. res.write).

So, we'll stick to the same example:

$scope.submit = function() {
    $http
        .post('/api/stickies', {stickie: $scope.stickie_text})
        .success(function(data){
            //what to do here? it's up to you and the data you write from server.
        })
        .error(function(data){
            console.log('Error: ' + data);
        });
};

Test this, and check your database.

Edit - suggested by @Kousha - Use a de-facto namespace for your form data (as you said formData beforehand - remember this is an example and you can use any name you want). It works like this:

  1. Give a prefix to each of your fields in the ng-model, so the same object holds the form data. Since you have only ONE field, it will be enough:

    ng-model="formData.stickie"
    

    deliberately I changed the variable name to match the name waiting in the nodejs server. Don't forget this, since I'll use the object directly as data.

  2. The final value of $scope.formData will be {stickie: whatEverIsInTheInputField}. If I added another field using ng-model="formDta.foo" as binding, the final value of $scope.formData would be {stickie: whatEverIsInTheInputField, foo: otherFieldValue}.

  3. I use the $scope.formData directly in the http request:

    $scope.submit = function() {
        $http
            .post('/api/stickies', $scope.formData)
            .success(function(data){
                //what to do here? it's up to you and the data you write from server.
            })
            .error(function(data){
                console.log('Error: ' + data);
            });
    };
    

  4. Although formData did not exist in the $scope beforehand, the binding created it implicitly before creating stickie under it.

这篇关于Angular:如何将$ scope变量传递给Node.js服务器。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆