I have an object $scope.foo in my controller. I want to watch for any changes in $scope.foo.bar and $scope.foo.baz and do a get request and replace all the data in $scope.foo object. Before this change happens, I would like to send the data of $scope.foo to the server with the old $scope.foo.bar and $scope.foo.baz.
$scope.$watch('foo.bar + form.baz', function() {
// send old $scope.foo to server with the
// previous $scope.foo.bar and $scope.foo.baz
});
How would I go about doing this? TIA
The second parameter of $scope.$watch is a function which receives two parameters : the first one is the new value, the second one the old value.
You can simply watch for the whole foo
object, and set the third parameter of $scope.$watch to true
in order to compare object for equality rather than for reference. Notice that this can be a pretty bad idea if your object is really large :
$scope.$watch(
'foo',
function (newFoo, oldFoo) {
// send old $scope.foo to server with the
// previous $scope.foo.bar and $scope.foo.baz
},
true
);
You can also watch separately foo.bar
and foo.baz
:
var sendAndReplace = function (parameterName, oldParameter) {
oldFoo = angular.copy($scope.foo);
oldFoo[parameterName] = oldParameter;
// send old oldFoo to server with the
// previous oldFoo.bar oldFoo.baz
};
$scope.$watch('foo.bar', function (newValue, oldValue)) {
sendAndReplace('bar', oldValue);
});
$scope.$watch('foo.baz', function (newValue, oldValue)) {
sendAndReplace('baz', oldValue);
});
The listener function which you provide to the $watch function has two parameters newValue and oldValue as described in the docs here: http://docs.angularjs.org/api/ng.$rootScope.Scope#$watch
In your example you watch on the concatenated string, so to parse the oldValues from the newValues you have to put a seperator between the two variables like so:
$scope.$watch('foo.bar + ";" + foo.baz', function(newValue, oldValue) {
var oldValues = oldValue.split(";");
var oldBar = oldValues[0];
var oldBaz = oldValues[1];
console.log("oldBar="+oldBar);
console.log("oldBaz="+oldBaz);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With