AngularJS在API回调后恢复表单

AngularJS Restes Form after API Callback

本文关键字:恢复 表单 回调 API AngularJS      更新时间:2023-09-26

在我的代码中,我有一个ng.resource:的工厂

.factory('company', function($resource){
return $resource(appHelper.apiPath('auth/company/info'), {}, {
    update: {
        method: "PUT"
    }
});
});

如果我在我的控制器中提交表单,只要api给出积极的响应,一切都很好。如果出现错误,api将返回一个带有http 200的json对象。在我的回调函数中,我验证响应:

$scope.saveCompanyForm = function (company) {
        company.$update(
            function(data) {
                    if(data.status == 'ERROR') {
                        alert("error from api")

                    } else {
                        alert("no error")
                    }
            }, function(error) {
                    alert("error")
    }

问题是,如果api返回一个错误,表单就会被清除。如果API响应为http 500或http 404,则不清除表单。是否有可能防止角度重置表单?谢谢最佳

您总是可以在回调之前保存并在回调之后应用。

$scope.saveCompanyForm = function (company) {
    var saved_company = company;
    company.$update(
        function(data) {
                if(data.status == 'ERROR') {
                    alert("error from api")
                    company = saved_company;
                } else {
                    alert("no error")
                    company = saved_company;
                }
        }, function(error) {
                alert("error")
                company = saved_company;
}