0

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

ghovat
  • 1,033
  • 1
  • 12
  • 38
  • Are you resetting the original data model to the scope model – Shintu Joseph Jul 27 '16 at 14:34
  • @ShintuJoseph No, I don't, in my controller function I fill the $scope.company_data: `$scope.company_data = goliathCompanyService.get();` And in my Form: `ng-submit="companyEditForm.$valid && saveCompanyForm(company_data)"` – ghovat Jul 27 '16 at 14:41

1 Answers1

1

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;
}
Gustavo Gabriel
  • 1,378
  • 2
  • 17
  • 28
  • I tried this already but if i make a console.log: `$scope.saveCompanyForm = function (company) { var saved_company = company; console.log(saved_company); company.$update( function(data) { if(data.status == 'ERROR') { alert("error from api") company = saved_company; console.log(company); ...` I get in both cases the response from the api: `m {status: "ERROR", status_code: 400, $promise: d, $resolved: true}` No idea why – ghovat Jul 27 '16 at 14:52
  • Thats because you are doing this, $scope.company_data = goliathCompanyService.get(); the get returns a promise, inside that promise is your actual object... You should get the object inside the promise and apply that to company like this: $scope.company_data = goliathCompanyService.get(); $scope.company = $scope.company_data.data; (or how the object is called) – Gustavo Gabriel Jul 27 '16 at 14:57