在Angular函数中调用AJAX

I have 2 problems with $http in function in this code.

$scope.buttonClick = function(){
    // Send input data
        $.post('lib/add_contact.php', $scope.contact, function(data){
            data = angular.fromJson(data);
            if(!data.error){
                $scope.contact = "";
                console.log('success');
            }else{
                console.log('error');
            }
        });

    // Next Code
    console.log('Next Code');
}

First problem is, when I want to clear a contact, it dont work immediately but only after I press key into input. If I put

$scope.contact = "";

outside of POST, It works well.

Second problem is, why is POST called last? Output of code is

Code Next
success

but i would like that output be

success
Code Next

Thanks for ideas and answers.

You are using jQuery for the ajax call which is happening outside the angular world. You need to trigger a digest cycle for the scope to update so the change is reflected in your view.

To fix the issue:

$scope.buttonClick = function(){
    // Send input data
        $.post('lib/add_contact.php', $scope.contact, function(data){
            data = angular.fromJson(data);
            if(!data.error){
                $scope.$apply(function(){ //<-- calling $apply()
                    $scope.contact = "";
                });
                console.log('success');
            }else{
                console.log('error');
            }
        });

    // Next Code
    console.log('Next Code');
}

However the preferred approach would to use the built in $http service included inside of angular which knows about angular and triggers the digest automatically.

Using $http (don't forget to add as a dependency to your controller)

$scope.buttonClick = function() {
    $http.post('lib/add_contact.php', $scope.contact).success(function(data) {
        data = angular.fromJson(data);
        if (!data.error) {
            $scope.$apply(function() { //<-- calling $apply()
                $scope.contact = "";
            });
            console.log('success');
        } else {
            console.log('error');
        }
    });
}