i have a (non-working) example in http://jsfiddle.net/S2kc7/1/
<radio ng-model="value" ng-value="foo">
<radio ng-model="value" ng-value="bar">
if a user does NOT approve, i'd like to revert to the previous state.
e.g., if ng-model="value" was on "foo" before the user clicked on "bar", and then the user chose to cancel, i'd like to prevent that event, and remain on "value=foo", without anything getting changed or $watched.
I tried:
$scope.$watch('value', function(){ newvalue = oldvalue })
$scope.clicked = function($event) { $event.preventDefault(); }
<radio ng-change="check_and_prevent()">
none of these methods were able to cancel the event (in my humle tests). some of the remains of the tests are commented out in the jsfiddle above.
can i prevent event on <radio>?
can i prevent event on <select> ?
EDIT @jose's answer worked for the case presented, but not in the real website;
In my website, "value" is actually a property of an object; but even that works out in jsFiddle's sterile environment: http://jsfiddle.net/L5555/
but not in my website.
I can't tell what's the difference, and i can't reveal my website.
thanks anyway.
The accepted answer does not covers scenerios which makes ajax calls on model change.
You can completely prevent changes by surrounding radio inputs with label tag.
<label ng-click="confirmChange($event)"><input type="radio" ng-model="value" value="foo" ></label>
$scope.confirmChange = function(event) {
if(!confirm('sure?')) {
event.preventDefault();
}
};
You can make it work by using ng-change. Make sure that each radio has the ng-change on it
<input type="radio" ng-model="value" value="foo" ng-change="validateChange()">
<input type="radio" ng-model="value" value="bar" ng-change="validateChange()">
<input type="radio" ng-model="value" value="zaz" ng-change="validateChange()">
And you can use this logic in your controller
$scope.value= $scope.preval= 'foo';
$scope.validateChange = function() {
if(confirm('revert??? value='+$scope.value+' preval='+$scope.preval)) {
$scope.preval = $scope.value;
} else {
$scope.value = $scope.preval;
}
};
Updated and working fiddle http://jsfiddle.net/S2kc7/3/
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