How can I denote which input fields have changed in AngularJS

前端 未结 7 1180
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 04:14

I\'m working on an edit form (user.html) that PUTs data to an API, but I\'d like to avoid PUTting all the data in the form. I\'d like to PUT just the changed items.

7条回答
  •  孤城傲影
    2020-12-05 04:57

    I often find that you will want more functionality when allowing users to update settings/information. Such as the ability to reset the information or cancel the edit and revert back. I know that was not part of the request, but when you consider this it makes other things easier.

    You store the saved values and also have the edited values, you can reset back to the saved values as they don't change. Then you can compare the 2 to determine what changed.

    Working Example: http://jsfiddle.net/TheSharpieOne/nJqTX/2/

    Look at the console log to see what changed when you submit the form in the example. It is an object that you can easily send via PUT.

    function myCtrl($scope) {
        $scope.user = {
            firstName: "John",
            lastName: "Smith",
            email: "john.smith@example.com"
        };
        $scope.reset = function () {
            angular.copy($scope.user, $scope.edit);
        };
        $scope.submitForm = function(){
            console.log(findDiff($scope.user, $scope.edit));
            // do w/e to save, then update the user to match the edit
            angular.copy($scope.edit, $scope.user);
        };
    
        function findDiff(original, edited){
            var diff = {}
            for(var key in original){
                if(original[key] !== edited[key])
                    diff[key] = edited[key];
            }
            return diff;
        }
    }
    

    Note: the findDiff is simple, it assume the two objects have the same keys and only the values have changed. We copy the objects so that they do not become 2 references to the same object, but in fact 2 objects.

提交回复
热议问题