Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : check if a model value has changed

IS there a way to check a dirty flag on the model itself, independent of the view?

I need the angular controller to know what properties have been changed, in order to only save changed variables to server.

I have implemented logic regarding if my entire form is dirty or pristine, but that is not specific enough

I could just slap a name and ng-form attribute on every input, to make it recognizable as a form in the controller, but then I end up with a controller that is strongly coupled with the view.

Another not-so appealing approach is to store the initial values that every input is bound to in a separate object, then compare the current values with the initial values to know if they have changed.

I checked Monitor specific fields for pristine/dirty form state and AngularJS : $pristine for ng-check checked inputs

like image 891
CodeToad Avatar asked Aug 25 '26 12:08

CodeToad


1 Answers

One option I could think of is

  1. As you get a model/object from service, create a replica of the model within the model and bind this new model to your view.

  2. Add a watch on the new Model and as the model changes, use the replica to compare old and new models as follows

    var myModel = {
        property1: "Property1",
        property2: "Property2",
        array1:["1","2","3"]
    }
    var getModel = function(myModel){
       var oldData = {};
       for(var prop in myModel){
          oldData.prop = myModel[prop];
       }
       myModel.oldData = oldData;
       return myModel;
    }
    var getPropChanged = function(myModel){
      var oldData = myModel.oldData;
      for(var prop in myModel){
       if(prop !== "oldData"){
        if(myModel[prop] !== oldData[prop]){
            return{
                propChanged: prop,
                oldValue:oldData[prop],
                newValue:myModel[prop]
            }
          }
        }
      }
    }
    
like image 104
Mothupally Avatar answered Aug 27 '26 02:08

Mothupally



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!