user3522457
user3522457

Reputation: 2963

$http scope issue with variable

$http({
    url: "php/myuId.php",
    method: "POST",
    data: {
        'userId': userId,
    },
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data, status, headers, config) {

        $scope.myId= data;
//return last inserted id
    }).error(function(data, status, headers, config) {
    });
//can't use it outside?
        $scope.user.push({
        "userId":  $scope.myId,

    });

strange, $scope.myId isn't change when I used it outside of scope $http, so I can't push my last inserted id to front end.

Upvotes: 0

Views: 330

Answers (2)

Zack Argyle
Zack Argyle

Reputation: 8407

The problem is that it is asynchronous, so you don't have the data yet until the promise returns. You could either put the $scope.user.push inside the success callback, or use $scope.$watch("myId"... to register when the value is updated.

Upvotes: 2

VtoCorleone
VtoCorleone

Reputation: 17203

Try using .apply(); The change in JS won't be seen, or reflected in the UI if you don't.

}).success(function(data, status, headers, config) {
    $scope.apply(function(){
        $scope.myId = data;
    });
})

Upvotes: 0

Related Questions