AngularJS - check if fields of model are the same with the initial values

1.6k views Asked by At

If I have the following object $scope.object1 which looks something like this:

{
 "firstName": "Name"
 "lastName": "Name"
 "startingDate": "08/Nov/2016"
 "endingDate": "16/Dec/2016"
 "description": "asd"
}

And I have a form which takes those values from backend and uses them on the input fields for date and description. The fields are editable so changing startingDate in the form field will change starting date in object1.

I need to display some content based on the initial values of $scope.object1 are the same with the values after submitting the form.

With other words, if nothing has changed.

How can I save the initial values of object1 and compare them with the values after modifying the form?

2

There are 2 answers

3
rob On

You can use angular.copy() to store the object before it is edited and angular.equals() to compare it with the modified version after it is edited

var objectBackup = angular.copy($scope.object1);
//...
if(angular.equal(objectBackup, $scope.object1) === false) {
    //The object has been modified
}
2
haran On

Angular have two different way to check changes in your objects.

1- checking if the form change if you use the object like ng-model in a form you can use the property $dirty.

<form name="myForm" ng-submit="processForm()" class="p-lg">
    //inputs
    <input type="text" id="firstName" ng-model="object1.firstName">
   //...
</form>

Controller

...
var objCopy = angular.copy($scope.object1);
...
$scope.processForm = function(){
  if($scope.myForm.$dirty){
    console.log('some field in the object change');
    //you can check the specific variable that you want and use the old one
  }
}
...

2- watch a object or specific key(that will be evaluate in every single digest)

//controller
     $scope.$watch('object1.firstName', function(newVal, oldVal){
            console.log('firstName change',oldVal, newVal );
        }, true);