0

How do I identify the change in value of a "radio button" before the current value change?

In my application, I need to alert the User about the effects that changing the value of this radio button will cause in the rest of form.

I've tried using ngChange and ngClick, but the value of the radio button is always changed (to the new value) even before I can do something with the current value.

Example:

       <form>
        <label>Nivel de gestão</label>
        <input name="gestao" type="radio" data-ng-model="nivelGestao" value="T" data-ng-change="mudarNivelGestao()">Tecnica
        <input name="gestao" type="radio" data-ng-model="nivelGestao" value="O" data-ng-change="mudarNivelGestao()">Operacional
        <input name="gestao" type="radio" data-ng-model="nivelGestao" value="I" data-ng-change="mudarNivelGestao()">Institucional

        <table>
            <tr>
                <td>Id</td>
                <td>Nome</td>
            </tr>
            <tr data-ng-repeat="gestor in gestores">
                <td>{{gestor.id}}</td>
                <td>{{gestor.nome}}</td>
            </tr>
        </table>

<script>
...
    $scope.mudarNivelGestao = function() {
        alert($scope.nivelGestao); // In this place the content has already been changed, but before I need to alert and ask if the User want continue, if "No" return to the last value, if "Yes" change the value and go ahead...
        ...
    }
...
</script>


    </form>
1
  • $scope.$watch('nivelGestao', function(newVal, oldVal, attr) { if(user need to change) {} else {$scope.nivelGestao=oldVal} }) you can watch for value like this Commented Aug 31, 2014 at 15:58

2 Answers 2

1

I answered a similar question here

Just surround the radio input with label and apply the confirm logic in labels ng-click event.

<label ng-click="confirmChange($event)"><input type="radio" ng-model="value" value="foo" ></label>

$scope.confirmChange = function(event) {
  if(!confirm('sure?')) {
    event.preventDefault();
  } 
};
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the mousedown event (which will fire before the click and change events).
E.g.:

<input type="checkbox" ng-model="option" 
       ng-mousedown="confirmOption($event)" />

$scope.confirmOption = function (evt) {
    var confirmMsg = 'Are you sure you want to select this ?';
    if (!$scope.option) {
        var confirmed = confirm(confirmMsg);
        $scope.option = confirmed;
    }
};

See, also, this short demo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.