简体   繁体   English

AngularJS在API回调后恢复表单

[英]AngularJS Restes Form after API Callback

in my code I have a Factory with ng.resource: 在我的代码中,我有一个带有ng.resource的Factory:

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

If I submit the form in my Controller everything works fine as far as the api gives a positive response. 如果我在控制器中提交表单,则只要api给出肯定的响应,一切都可以正常工作。 In case of an error the api returns a json object with http 200. In my callback function I validate the response: 如果发生错误,则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")
    }

The problem is if the api returns an error the form cleared. 问题是,如果api返回错误,则表单已清除。 If the API response with http 500 or http 404 the form is not cleared. 如果API响应使用http 500或http 404,则不会清除该表单。 Is there any possibility to prevent angular to reset the form? 有没有可能防止角度重置表格? Thanks best 最好的谢谢

You can always save it before and apply after the callback. 您始终可以在回调之前保存它并在回调之后应用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM