I changed the scope variable in an if statement and outside the if statement it turned into an undefined variable
app.controller("Login", function($scope, $window,$http){
var status;
$scope.loginUser = function(logData){
$http.post('/corporate/login',logData).then(function(response){
var data = response.data
var status = data.success;
if(status == true){
$scope.logStatus = true;
console.log($scope.logStatus); // prints true
}else{
$scope.logStatus = false;
}
})
console.log($scope.logStatus); //prints undefined
}
});
It did not "turn into" an
undefined
value. The lastconsole.log
in the code executes before the console.log in the success handler. It isundefined
because it has not yet been set by the success handler.Expaination of Promise-Based Asynchronous Operations
The console log for "Part4" doesn't have to wait for the data to come back from the server. It executes immediately after the XHR starts. The console log for "Part3" is inside a success handler function that is held by the $q service and invoked after data has arrived from the server and the XHR completes.
For more information, see How to use $http promise response outside success handler.
Demo
$http
is asynchronous. Yourif/else
conditions are in the success callback. Problem is that theconsole.log($scope.logStatus);
line is called before the success callback gets calledYou should probably initialise
$scope.logStatus = false
before the$http
call.EDIT:
If like you said,
$scope.logStatus
remains false, then check if your if block is being called. See fiddle:https://jsfiddle.net/51bsbzL0/253/