0

I have 2 radio buttons, then is ng-change event is applied on NO radio button.

I am showing a confirmation box , on ng-change event of NO radio button.

if he click cancel, Then I want to check the Yes Radio button.

But it's not working .

HTML

<body ng-app="myapp" ng-controller="MyCtrl">
  <div>
    Yes:
    <input type="radio" ng-model="ModelVal" value="true" name="ff">
    <br>No:
    <input type="radio" ng-model="ModelVal" value="false" ng-change="chck('ModelVal')" name="ff">


    <br>
    <hr>{{ModelVal}}

    <div ng-if="ModelVal == 'true'">Helll</div>
  </div>

</body>

JS

// Code goes here
var myapp=angular.module('myapp',[]);
myapp.controller('MyCtrl',function($scope){
  $scope.ModelVal='true';
 $scope.chck=function(chkM){

   var getV=confirm('Sure to Cancel ?');
  if(getV) {
            $scope[chkM]='false';

        }else {
           $scope[chkM]='true';

        }
 };

});

as you can see from demo, after clicking on NO radio button, I'm not changing model, unless he click on OK or cancel.

PLUNKER

Getz
  • 3,983
  • 6
  • 35
  • 52
Amit Kumar
  • 5,888
  • 11
  • 47
  • 85

1 Answers1

2

Using a $timeout() seems to have solved the problem

// Code goes here
var myapp = angular.module('myapp', []);
myapp.controller('MyCtrl', function ($scope, $timeout) {
    $scope.ModelVal = 'true';
    $scope.chck = function (chkM) {
        var getV = confirm('Sure to Cancel ?');
        $timeout(function () {
            $scope[chkM] = getV ? 'false': 'true';
        })
    }
});

// Code goes here
var myapp = angular.module('myapp', []);
myapp.controller('MyCtrl', function($scope, $timeout) {
  $scope.ModelVal = 'true';
  $scope.chck = function(chkM) {
    var getV = confirm('Sure to Cancel ?');
    $timeout(function() {
      $scope[chkM] = getV ? 'false' : 'true';
    })
  }
});
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js"></script>
<div ng-app="myapp" ng-controller="MyCtrl">
  <div>
    Yes:
    <input type="radio" ng-model="ModelVal" value="true" name="ff">
    <br>No:
    <input type="radio" ng-model="ModelVal" value="false" ng-change="chck('ModelVal')" name="ff">


    <br>
    <hr>{{ModelVal}}

    <div ng-if="ModelVal == 'true'">Helll</div>
  </div>

</div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • @AmitKumar not really sure why? but it looks like some how the watches attached to the input model is not fired in your case – Arun P Johny Feb 12 '15 at 05:23