Domanda

I'm working on an AngularJS project that uses an API to deal with data. Now I'm implementing the 'create' functionality using $resource. Everything was going well except the naming conversion: I use camelCase but the API accepts snake_case only. Is there a way to automatically convert these keys to snake_case?

Service:

services.factory('Salons', ['$resource',
    function ($resource) {
        return $resource('/salons/:slug', {
            slug: "@slug"
        });
    }
]);

Controller:

controllers.controller('CreateSalonController', ['$scope', 'Salons',
    function ($scope, Salons) {
        $scope.submit = function() {
            Salons.save(this.salon);
        };
    }
]);

View:

<form name="salonForm" role="form" ng-submit="submit()">
    <div class="form-group">
        <label for="salonContactFirstName">First name</label>
        <input name="contactFirstName" type="text" class="form-control" id="salonContactFirstName" data-ng-model="salon.contactFirstName" />
    </div>
...
È stato utile?

Soluzione

I have not found any built-in solution so I implemented one:

A new service:

services.factory('Util', function () {
        var Util = {
            stringToSnakeCase: function (input) {
                return input.replace(/([0-9A-Z])/g, function ($1) {
                    return "_" + $1.toLowerCase();
                });
            },
            objectKeysToSnakeCase: function (input) {
                var output = {};
                _.each(input, function (val, key) {
                    output[Util.stringToSnakeCase(key)]
                        = _.isObject(val) ? Util.objectToSnakeCase(val) : val;
                });
                return output;
            }
        };
        return Util;
    }
);

And the updated controller:

controllers.controller('CreateSalonController', ['$scope', 'Salons', 'Util',
    function ($scope, Salons, Util) {
        $scope.submit = function() {
            Salons.save(Util.objectKeysToSnakeCase(this.salon));
        };
    }
]);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top