How can I denote which input fields have changed in AngularJS

前端 未结 7 1128
被撕碎了的回忆
被撕碎了的回忆 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 05:05

    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
    
    0 讨论(0)
提交回复
热议问题