angularJS: how to revert / prevent radio button event?

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

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.

回答1:

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/



回答2:

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();    }  }; 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!