简体   繁体   中英

AngularJS 'PUT' requests. How to submit ONLY the data in form?

I'm trying to update user data, but when I make the 'PUT' request, Angular is sending the entire user $scope rather than just the fields exposed by the form.

I'm using a Factory to get and put the data. Here's my edit function

$scope.editStudent = function () {
    Student.edit ({id: $stateParams.studentId}, $scope.Student, function (data) {
        $location.path('/');
});
};

This doesn't work for me because the server I'm sending to does it's own server-side validation, and if I'm sending the entire student scope there will be some fields that are blank, thus will not pass validation.

The server allows me to send just the field I need to update, so I'm looking for an Angular way of doing this.

Here's a screenshot to help explain my question:

You can write function to check the field defined in the form and then only submit the value. I think the code is self explanatory.

Code Snippet

app.controller('MainCtrl', function($scope, $http) {
    $scope.user = {
        "name": "Ali",
        "company": "MSB",
        getData: function(form) {
            var data = {};
            angular.forEach(this, function(fieldValue, fieldName) {
                if (!angular.isFunction(fieldValue) && form.$isSubmit(fieldName)) {
                    data[fieldName] = fieldValue;
                }
            });
            return data;
        }
    }

    $scope.save = function() {
        $scope.userForm.$isSubmit = function(fieldName) {
            return !angular.isUndefined((this[fieldName]));
        }
        console.log($scope.user.getData($scope.userForm));
        $scope.data = $scope.user.getData($scope.userForm);
        //$http.put('url', $scope.data)
    }
});

I created the plunkr - http://plnkr.co/edit/6g5myBvBmWZ2IvKMLuvL?p=preview

*Tips (or rules)

  1. input name must same as the model name
  2. change getData function as you like to process which data to return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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