angularJS: how to revert / prevent radio button event?


i have a (non-working) example in

<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:

but not in my website.

I can't tell what's the difference, and i can't reveal my website.

thanks anyway.

Problem courtesy of: Berry Tsakala


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

Solution courtesy of: JoseM


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?')) {
Discussion courtesy of: Kerem Demirer

This recipe can be found in it's original form on Stack Over Flow.