not able to access $scope object outside a http response callback function in angularjs

后端 未结 3 1920
野趣味
野趣味 2021-01-17 02:51

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

相关标签:
3条回答
  • 2021-01-17 03:05

    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.

    0 讨论(0)
  • 2021-01-17 03:07

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

    0 讨论(0)
  • 2021-01-17 03:08

    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() { }).
    0 讨论(0)
提交回复
热议问题