最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular: how to pass $scope variables into the Node.js server. - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Jul 30, 2014 at 18:01 user3727514 asked Jul 29, 2014 at 21:38 user3727514user3727514 2733 gold badges6 silver badges14 bronze badges 3
  • you already have the data in the ng-model – Luis Masuelli Commented Jul 29, 2014 at 22:03
  • @LuisMasuelli what do you mean by that? With ng-model="stickie_text". how can I pass this stickie_text variable into my app.post function so that I can update the db with it? – user3727514 Commented Jul 29, 2014 at 22:07
  • I'm writing an answer – Luis Masuelli Commented Jul 29, 2014 at 22:07
Add a ment  | 

1 Answer 1

Reset to default 8

When you use ng-model it is to bind your form ponents 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 ponent 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 ment 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 pose 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.

发布评论

评论列表(0)

  1. 暂无评论