How can I denote which input fields have changed in AngularJS

这一生的挚爱 提交于 2019-11-27 19:17:56

If you put the input in a form with a name attribute and then give the input a name attribute, you can also access the input's $pristine property.

<div ng-controller="MyController">
  <form name="myForm">
    <input type="text" name="first" ng-model="firstName">
    <input type="text" name="last" ng-model="lastName">
  </form>
</div>
app.controller('MyController', function($scope) {
  // Here you have access to the inputs' `$pristine` property
  console.log($scope.myForm.first.$pristine);
  console.log($scope.myForm.last.$pristine);
});

You can use $scope.myForm.$pristine to see if any fields have changed, and the $pristine property on each input's property on the form to see if that input has changed. You can even iterate over the myForm object (non-input-field objects have keys prefixed with a $):

angular.forEach($scope.myForm, function(value, key) {
  if(key[0] == '$') return;
  console.log(key, value.$pristine)
});
// first, true
// last, false

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.

old thread but to build on TheSharpieOne's answer, you may want to check for equality using angular.equals instead of "===" otherwise this won't work for arrays.

function findDiff(original, edited){
  var diff = {}
    for(var key in original){
      if(!angular.equals(original[key], edited[key]))
        diff[key] = edited[key];
    }
    return diff;
}

You can use $scope.$watch('scopeVariable', function(oldValue, newValue)...) and build an object containing only newValues that are different than oldValues.

Here's a link to Angular docs regarding $watch.

Building off ARN and TheSharpieOne's answers. If you are using underscore in your project you could take this approach for finding differences in arrays of objects.

function findDiff(original, edited){
    _.filter(original, function(obj){ return !_.findWhere(edited, obj); });
}

A simple way to retrieve an object only with changed values on submit event:

var dirtyInput = $('#myForm .ng-dirty');
var change = {};

for (var i = 0; i < dirtyInput.length; i++) {
  change[dirtyInput[i].name] = dirtyInput[i].value;
}

Adding more to TheSharpieOne's answer. The diff between original and edited could also be due to new fields added in the edited object. Hence additional check for the same

function findDiff(original, edited){
    var diff = {}
    for(var key in original){
      if(!angular.equals(original[key], edited[key]))
        diff[key] = edited[key];
    }
    for(var key in edited){
      if(!angular.equals(original[key], edited[key]))
        diff[key] = edited[key];
    }

    return diff;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!