在 Angular 函数中调用 AJAX

Call AJAX in Angular function

我在这段代码中的函数 $http 有 2 个问题。

$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');
}

第一个问题是,当我想清除联系人时,它不会立即起作用,而是在我按下输入键后才会起作用。 如果我把

$scope.contact = "";

在 POST 之外,效果很好。

第二个问题,为什么最后调用POST?代码输出为

Code Next
success

但我希望输出是

success
Code Next

感谢您的想法和答案。

您正在使用 jQuery 进行发生在 angular 世界之外的 ajax 呼叫。您需要触发范围更新的摘要周期,以便更改反映在您的视图中。

解决问题:

$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');
}

然而,首选方法是使用 angular 中包含的内置 $http 服务,该服务了解 angular 并自动触发摘要。

使用 $http(不要忘记将其作为依赖项添加到您的控制器)

$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');
        }
    });
}