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?
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;
});
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.