0

I am trying to do a http post using AngularJS but angular is not converting my $scope variable to JSON.

Here is my code:

        $http({
                method: "POST",
                url: "/Account/Login",
                data: $scope
            })

Which results in the request POST message having

"$SCOPE"

but if I change it to output any of my scope properties, it is sending the message with correct properties, e.g.:

        $http({
                method: "POST",
                url: "/Account/Login",
                data: { email: $scope.email, password: $scope.password }
            })

Which results in the request POST message having

{"email":"[email protected]","password":"asd"}

Do I always have to wrap my requests like this? Or is there a way to tell AngularJS to send all properties on scope? Any Pro's / Con's?

1
  • 1
    don't use $scope. Use an inner object like $scope.data which has data.email and data.password. It does say to do this in the manual because ngIf and ngRepeat will isolate your primitive scope variables. Commented Jan 31, 2015 at 16:59

1 Answer 1

6

Sending the $scope is not a good idea, It contains lot more than your email and password

You should create a property like $scope.user and then attach the model to it like $scope.user.email. Now you can send it using $scope.user

$http({
     method: "POST",
     url: "/Account/Login",
     data: $scope.user
})

a lil about $scope

scope is an "object" that "binds" to DOM element where you apply controller. All child elements can read and modify scope data (unless you modify primitives in new scopes or they're isolated

for more official doc is they way

Sign up to request clarification or add additional context in comments.

2 Comments

I was doing that earlier, (having a formData object inside scope) but then that means everything in my form needs to bind to formData.email, etc.
Is tehre anyway to change $scope or the root of t he bindings of inner objects inside a form? E.g. bindg form to $scope.user, and then on inputs have only ng-model="email" which would be bound to $scope.user.email?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.