3

I use AngularJs and I need to return a data after a $http.post connection. This is the code:

app.controller('PrincipalController',['$http', '$scope', function($http,$scope){
  $scope.myData = 0;
  $http.post("server/checklogin.php",
    {id: "id",email: "email",password: "password"}
  )
  .success(function(data){
    console.log($scope.myData) //0
    $scope.myData = data;
    console.log($scope.myData); // 1
}

OLD: How can I pass the data into myData? - Thanks for your answers and sorry if I haven't explained well.

But now, in html, {{myData}} what can I write?

I do not know if it's fundamental, but I'll have to use "myData" with an "ng-if"..

EDIT: Thanks! I think that I've solved! :D

5
  • Sorry i cannot understand the question, you just do 'myData = data' inside the 'success' function, what's the problem? Commented Feb 12, 2015 at 11:22
  • Whatever you wish to do with data has to be with in success. You cannot take it outside because of the async nature. Commented Feb 12, 2015 at 11:25
  • The only angularish way to do what you want, i.e. using asynchronously retrieved data in a synchronous way is to use the $resource service which will fill in your myData variable (provided it is in the $scope) when the data is back from the server. $http does not provide this functionality right away and the only place where you can use the data returned is in the callback. Commented Feb 12, 2015 at 11:28
  • either use this.myData or $scope.myData not both Commented Feb 12, 2015 at 12:02
  • @entre ok.. But it doesn't works.. What do I do? Commented Feb 12, 2015 at 12:14

2 Answers 2

7

Typically in your service you will return the promise

myService.getCheckLogin = function {
    return $http.post("server/checklogin.php",
      {id: "id",email: "email",password: "password"}
      );
}

then in controller

myService.getCheckLogin()
.success(function(data){
  $scope.myData = data;
}
.error(function(err){
  console.log(err);
}
Sign up to request clarification or add additional context in comments.

1 Comment

shouldn't be closing ')' of success method before .error call?
2

you should do something like this:

.success(function(data){
    $scope.myData = data;
    //OR
    myCallback(data);
    console.log(data) //data = 1 (server works);
}

You cannot put the assignment right after the post call, because the call is asynchronous, you cannot predict the exact moment when it will be returning.

I used the $scope, because normally you might use it through a service on a controller where a scope is available. Otherwise you can use a function in a callback

Comments

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.