Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 316
brock Avatar asked Sep 05 '13 16:09

brock


People also ask

Which property of ngModel is set to true when an input value is modified by user?

By setting the allowInvalid property to true, the model will still be updated even if the value is invalid.

What is the use of ngModelOptions?

The ng-model-options directive is used to control the binding of an HTML form element and a variable in the scope. You can specify that the binding should wait for a specific event to occur, or wait a specific number of milliseconds, and more, see the legal values listed in the parameter values below.

Which property states that the form input has been used in Angular JS?

Form input fields have the following states: $untouched: It shows that field has not been touched yet. $touched: It shows that field has been touched. $pristine: It represents that the field has not been modified yet.

How do I make a field editable in Angularjs?

To create editable select (dropdown) just set editable-select attribute pointing to model. To pass dropdown options you should define e-ng-options attribute that works like normal angular ng-options but is transfered to underlying <select> from original element.


1 Answers

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 
like image 62
Michelle Tilley Avatar answered Oct 02 '22 09:10

Michelle Tilley