brock brock - 2 months ago 13
AngularJS Question

How can I denote which input fields have changed in AngularJS

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.

I've seen the use of dirty and pristine when working with forms, but this applies to any change in the form. I've also seen the use of ng-change, but I don't want to trigger an action on a change to one element, just denote that the changed element should be included in the PUT.

Anyone found a way to denote only the input fields that have changed?


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">
app.controller('MyController', function($scope) {
  // Here you have access to the inputs' `$pristine` property

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