0

I have some objects that are retrieved from a web api and are "editable". When the user edit one object he is able to change some fields. I would like to maintains a isDirty field on those objects to know when they are modified (isDirty==true).

I wonder if I can rely on the AngularJs changes detection mechanism to set this field on my objects ?

gervais.b
  • 2,294
  • 2
  • 22
  • 46
  • yes, you can use ng-form and then call $dirty to check if form is dirty or if you want to set it on those objects i think you can use $watch – Harry Nov 30 '16 at 13:45
  • I would like to set it on those objects yes. The problem with `$watch` is that if trigger the listener when `$watch` is applied. And because `isDirty` may already be set to true (local storage) I have no (clean) means to detect this false modification. – gervais.b Nov 30 '16 at 14:06
  • i think the watch only triggers if something changes, Documenation "Registers a listener callback to be executed whenever the watchExpression changes." – Harry Nov 30 '16 at 15:31
  • I'm sorry but it triggers the first time : http://jsfiddle.net/m20n7mtL/. From the documentation sample "// the listener is always called during the first $digest loop after it was registered" https://docs.angularjs.org/api/ng/type/$rootScope.Scope – gervais.b Dec 01 '16 at 07:11
  • 1
    There is a complete paragraph about that with a workaround from the documentation : "After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization." (http://jsfiddle.net/eo007rrj/) – gervais.b Dec 01 '16 at 07:15

0 Answers0