ghovat
ghovat

Reputation: 1043

AngularJS Restes Form after API Callback

in my code I have a Factory with ng.resource:

.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. In case of an error the api returns a json object with http 200. In my callback function I validate the response:

$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. If the API response with http 500 or http 404 the form is not cleared. Is there any possibility to prevent angular to reset the form? Thanks best

Upvotes: 0

Views: 151

Answers (1)

Gustavo Gabriel
Gustavo Gabriel

Reputation: 1296

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

Upvotes: 1

Related Questions