1

I have a form which when loaded sends GET request to server and recives data which will stored in 'master' and i copy that data to 'local' as below.

$scope.dirty = false;

init(data);

function init(data) {
    $scope.master = angular.copy(data.data);
    $scope.local = angular.copy($scope.master);
}

Now, I use local object as model for my form and I have to button submit and reset. I watch the local object as below.

  $scope.$watchCollection('local', function (newLocal, oldLocal) {
    $scope.dirty = !angular.equals(newLocal, $scope.master);
});

So, If dirty is true then i can know that data has been modified but since I am using Objects AngularJS adds $$hasKey to $scope.local and because of that $scope.dirty always sets to true.

So, is there any way to handle this problem? I am new to AngularJS so may be this can be funny question but I'm stuck.

2 Answers 2

1

You could convert your object to a JSON string before comparing:

function init(data) {
    // store json data into $scope.master for later comparison
    $scope.master = angular.toJson(data.data);
    $scope.local = angular.copy(data.data);
}

$scope.$watchCollection('local', function (newLocal, oldLocal) {
    var json = angular.toJson(newLocal); // new local without $$ key
    $scope.status.dirty = !angular.equals(json, $scope.master);
    // $scope.local is still a javascript object
});
Sign up to request clarification or add additional context in comments.

7 Comments

If I use this code then $scope.local = angular.copy($scope.local) wont work. So, I must use $scope.local = angular.copy(data.data) right ?
how so ? you could introduce another variable then?
What do you mean, it does not work? It does not do what you want, or it throws an error? Plus, in your post, you mention $scope.dirty but you have $scope.status.dirty, is it a spelling mistake?
Yes that was my mistake. After using your code $scope.dirty still has true value.
Can you add console.log() statements to see the temporary results?
|
0

I was sending data form PHP and PHP treats Number and string as seperate datatype. So I converted those Number data to string and now It works as desired and also I leart that whenever I use <form name='newForm> angularJS creates a new scope named newForm so that I can you many properties of that scope like $dirty, $pristinem $submitted and many more. so Now I dont have to write this logic by myself

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.