angularjshttp-postdynamic-scope

AngularJS is not updating dynamic scope variable in http post success


I'm trying to get data from database and assign it to a dynamic scope variable with a function but it doesn't assign the data to the dynamic variable at first attempt. Can anyone help?

This is my dynamicScope function;

$scope.dynamicScope= function(name, data){
  var modelScope = $parse(name);
  modelScope.assign($rootScope, data);
};

and here is postService function;

$scope.postService = function(scopeName, sentData){
    $http.post($scope.serviceLink, sentData)
            .success(function (data, status) {
              console.log("Fetched data: " + data);
              $scope.dynamicScope(scopeName, data);
            })
            .error(function (errData, status) {
               console.log("Error: "+errData);
            });
};

When I call postService as

$scope.postService("userInfo", loginData);

It prints data from the postService but it gives an error when I want to print it after the previous line like here console.log($scope.userInfo[0].user_name); it says $scope.userInfo is undefined. But it fetches previous data in the second attempt. Thanks in advance.


Solution

  • Return the $http promise to the function:

    $scope.postService = function(scopeName, sentData){
        ͟r͟e͟t͟u͟r͟n͟ $http.post($scope.serviceLink, sentData)
                .then(function (response) {
                  var data = response.data;
                  console.log("Fetched data: " + data);
                  $scope.dynamicScope(scopeName, data);
                  return response.data;
                })
                .catch(function (response) {
                   var errData = response.data;
                   console.log("Error: "+errData);
                   throw response;
                });
    };
    

    Then use that promise to delay the console.log:

    var promise = $scope.postService("userInfo", loginData);
    promise.then(function(data) {
        console.log(data);
        console.log($scope.userInfo[0].user_name);
    });