Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  28] [ 3]  / answers: 1 / hits: 17337  / 10 Years ago, tue, november 18, 2014, 12:00:00

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


More From » angularjs

 Answers
2

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]
    }
    }
    }
    }
    }


[#68774] Friday, November 14, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianom

Total Points: 601
Total Questions: 98
Total Answers: 109

Location: Kenya
Member since Fri, Dec 23, 2022
1 Year ago
lucianom questions
Tue, Feb 22, 22, 00:00, 2 Years ago
Wed, May 5, 21, 00:00, 3 Years ago
Sun, Jan 24, 21, 00:00, 3 Years ago
Sat, Aug 15, 20, 00:00, 4 Years ago
Mon, Jun 22, 20, 00:00, 4 Years ago
;