I have this controller for saving some details for an individual. I have a separate repository EntityRepository where a function to get the user gender from database is defi
The reason why you can't access the value of $scope.userGender
outside the AJAX success callback is simple: AJAX is asynchronous, meaning that a value to this variable will be assigned only after this AJAX call succeeds. You should adapt your code so that it doesn't depend on the value of $scope.userGender
before this AJAX call has succeeded. If this value is data bound to some control in the markup, then this is not a problem, the value will appear with a little delay when the value is retrieved from the server.
Can you try this.
$scope.GetUserGender = function(){
EntityRepository.getUserGender().then(function(response){
$scope.userGender = response.data.gender;
console.log("inside : ", $scope.userGender);
}).catch(function(errorResponse) {
$scope.error = errorResponse.data
});
}
$scope.GetUserGender(); //
console.log("outside : ", $scope.userGender);
Hope this will work :)
You are not able to access the value outside due to asynchronous property of requests. What that simply means is that this statement: console.log("outside : ", $scope.userGender);
, is getting executed before the .then(function(){ ... })
.
Fixes:
$timeout
.controller('individualDetailsCtrl', function($scope, $rootScope, $location, EntityRepository, $timeout) {
and
$timeout(function() {console.log("outside : ", $scope.userGender)});
$scope.userGender
's value only inside the .then(function() { })
.