javascriptangularjsapirestangularjs-ng-resource

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


Solution

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