0

If i do:

scope.$watch('obj', function(newObj, oldObj) {
  //...
}, true);

How do I find the key-value pair in the object that changed?

.

Only to understand what I try to do:

I have an object of the form:

scope.actions = {
  action1: false,
  action2: false
}

When the boolean changes, I want to assign function calls to it. Something like, DO-action - UNDO-action.

So I watch it the following way:

scope.$watch('actions', function(newObj, oldObj) {

  /*PSEUDO CODE START*/

  IF (action1 changed && action1 true) {
    do-func1();
  }
  IF (action1 changed && action1 false) {
    undo-func1();
  }
  ...
  /*PSEUDO CODE END*/

}, true);

My problem here is, that if I check the values for their boolean, all the functions get called. So the point here is, how do I find the changed key-value pair in the object?

1
  • Do you have only 2 actions, or there might be arbitrary number of actions? Commented Jun 19, 2015 at 14:11

1 Answer 1

1
scope.$watch('actions', function(newActions, oldActions) {
    for(var i in newActions) {
        if(newActions.hasOwnProperty(i)) {
            var newAction = newActions[i];
            var oldAction = oldActions[i];

            if(newAction !== oldAction) {
                if(newAction === true) {
                    doActions[i](); // do-func-i();
                } else if (newAction === false) {
                    undoActions[i](); // undo-func-i();
                }
            }
        }
    }
}, true);

doActions here is a conventional map of actions

doActions = {
    action1 : function() {
        console.log('action1');
    },
    action2 : function() {
        console.log('action2');
    }
}

doActions['action1'] will reference first function

You may have an array as well, but then you'll need to introduce an index to fetch proper function doActions[0]

Sign up to request clarification or add additional context in comments.

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.