I have a select box that triggers an http PUT when it's changed.
<select ng-model='color'></select>
$scope.$watch('color', function(newValue, oldValue) {
$http.put('...', {color: newValue})
});
The issue is that if the http request fails for whatever reason I want the select box to revert to it's previous value.
$scope.$watch('color', function(newValue, oldValue) {
req = $http.put('...', {color: newValue})
req.error(function(){
$scope.color = oldValue // will probably cause the $watch to get triggered again (bad)
});
});
This will probably cause the $watch function to get triggered again which is not desirable as it would trigger an unnecessary PUT.
How can I revert the value without triggering the $watch function again?
In angularjs $watch () function is used to watch the changes of variables in $scope object. Generally the $watch () function will create internally in angularjs to handle variable changes in application.
In angularjs $watch() function is used to watch the changes of variables in $scope object. Generally the $watch() function will create internally in angularjs to handle variable changes in application. Suppose in our angularjs applications if we want to create custom watch for some actions then it’s better to use $scope.watch function.
The AngularJS $watchCollectionmethod is used to observe properties on a single object and notify you if one of them changes. In other word watchCollection is shallow watches the properties of an object and fires whenever any of the properties change.
Once a watcher is configured with the scope, the listener function is called to initialize the watcher. This method is for watching changes of scope variables. This method has callback function which gets called when the watching properties are changed.
Use ng-change
to submit the changes to the server and revert back to the previous value if the put fails.
<select ng-model='color' ng-change="changeColor()"></select>
$scope.$watch('color', function(newValue, oldValue) {
$scope.previousColor = oldValue;
});
$scope.changeColor = function(){
$http.put('...', {color: $scope.color}).error(function(){
$scope.color = $scope.previousColor;
});
};
Plunker
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