Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular data is not binding in $http.post success method

I found one weird issue while working in angular js I am getting data using ajax call. I am binding data to $scope object but view is not getting updated after data bind following is my code

  $scope.getPlanDetail = function (){

    $rootScope.planBody.checkUpdate= false;
    $http.post('http://MyServerURL',JSON.stringify($rootScope.planBody)).
          success(function(response){
              $scope.dataVal = response;//Able to view data in console;
              console.log($scope.dataVal)//data json shown in log window
              localStorage.setItem("tempDataVal", JSON.stringify(response));//able to set data in localStorage;
          }
  }

getPlanDetail() function is getting called on btn click using ng-click

Same functionality I have done in other case(using get method.) where code is working properly. The only diff I found is that current AJAX call is taking to much of time because of too much of server side processing and its post method I am not sure whether this(using post method) is causing issue in binding

On same view(.html) I added dummy button ng-click event. After ajax success call I click on button and view is loaded because of data use from localStorage variable.

$scope.dummyClick= function(){
    console.log($scope.dataVal);//giving Undefined
    $scope.dataVal = JSON.parse(localStorage.getItem("tempDataVal"));// this time view binded properly.
}

I didn't understand why data is not bind to view in success method. Does the $scope time out after some time if server takes too much time to respond?

Thanks in Advance.

like image 737
Sanket Avatar asked Nov 10 '22 05:11

Sanket


1 Answers

If you are changing the model inside an ajax call then you need to notify the angular js that you have some changes.

$scope.$apply(); after the below line will fix your issue. This line will update the scope.

$scope.dataVal = response;

Thanks,

Santyy

like image 192
Santyy Avatar answered Nov 15 '22 07:11

Santyy