I am new to angularjs and trying to assign the data from http request function to $scope variable. but due to asynchronous, this line of code console.log($scope.field_result_var ) will be execute before it the request done
app.controller('my_control', function($scope, $http) {
$scope.field_result_var ='';
$scope.check_field_http = function() {
$http({
method: 'GET',
url: 'aaa.php',
params : {field:$scope.field_data}
}).then(function successCallback(response) {
$scope.field_result_var = response.data;
}, function errorCallback(response) {
});
};
$scope.check_field = function() {
$scope.check_field_http ();
//below is code need to execute after get the data like
console.log($scope.field_result_var );
};
});
I have tried to use callback function based on the answer in AngularJS http return value, but I might implement the callback function incorrectly, thus the console.log($scope.field_result_var ) still execute before it the request done
app.controller('my_control', function($scope, $http) {
$scope.field_result_var ='';
$scope.check_field_http = function() {
$http({
method: 'GET',
url: 'aaa.php',
params : {field:$scope.field_data}
}).then(function successCallback(response) {
myCallbackFunction(response);
}, function errorCallback(response) {
});
};
$scope.check_field = function() {
$scope.check_field_http ();
//below is code need to execute after get the data like
console.log($scope.field_result_var);
};
function myCallbackFunction(response_param) {
$scope.field_result_var = response_param.data;
}
});
I am sorry that I have few question here, some might be general concept for angularjs:
1) What is the mistakes I made for the callback implementation to ensure the console.log will execute after the $http request success?
2) If I defined the callback function like, how to call it for my case?
$scope.myCallbackFunction = function (response_param) {
$scope.field_result_var = response_param.data;
}
3) What is the difference between
$scope.myCallbackFunction = function (response_param) {
$scope.field_result_var = response_param.data;
}
and
function myCallbackFunction(response_param) {
$scope.field_result_var = response_param.data;
}
in angularjs?
4) When searching the solution, I saw people create http request inside myApp.factory like How to wait till the response comes from the $http request, in angularjs?
What is the difference between create a function with myApp.factory vs create a function using $scope.function_name = function()