not able to access $scope object outside a http re

2019-02-21 01:16发布

问题:

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 defined.

The function response is working correctly and when I am printing the gender on console inside the function response it works(console.log("inside : ", $scope.userGender);).

But outside the function the value is not undefined I am getting(console.log("outside : ", $scope.userGender);)

.controller('individualDetailsCtrl', function($scope, $rootScope, $location, EntityRepository) {
 $scope.userGender = "";
 $scope.entity = {
   name: "",
   gender: $scope.userGender,
   dob: "",
   pan: ""
 };
 EntityRepository.getUserGender()
 .then(function(response){
   $scope.userGender = response.data.gender;
   console.log("inside : ", $scope.userGender);
 })
 .catch(function(errorResponse) {
   $scope.error = errorResponse.data
 });
 console.log("outside : ", $scope.userGender);
});

I want to save the gender from the response in the $scope.entity.gender but I am not able to access the value of $scope.userGender outside the function scope.

Since $scope is defined in the scope of controller I think it should be able to access its values outside the function response.

回答1:

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.



回答2:

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:

  1. Wrap your outside code inside of $timeout

.controller('individualDetailsCtrl', function($scope, $rootScope, $location, EntityRepository, $timeout) {

and

$timeout(function() {console.log("outside : ", $scope.userGender)});

  1. Use $scope.userGender's value only inside the .then(function() { }).


回答3:

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 :)