Cancel button click doesn't complete

555 Views Asked by At

When I open a modal dialog and without making a change, I click on cancel button, I expect the dialog to close.

But in case I have a validation on the textbox currently in focus, the validation text still appears when the focus moves out of the text box. The mentioned behavior can be seen in the following plunker -

https://plnkr.co/edit/5VsL59iCh7smS1wfEwFZ

<input type="text" autofocus ng-model="$ctrl.textValue" ng-blur="$ctrl.validate()">

Also, as reproducible in the above link, if I click on the cancel button near the top of the button, the click never completes (though the focus is shifted to the button) and the modal dialog does not close.

Any suggestion on how I can make sure that the click on the button completes or if the blur event can be avoided in case the dialog is being cancelled.

2

There are 2 best solutions below

7
On BEST ANSWER

You can call $ctrl.validate() inside $ctrl.ok() function. So ng-blur can also be removed.

  $ctrl.ok = function () {
    $ctrl.validate ();
     if(!$ctrl.textValue) {
      $ctrl.invalidControl = true;
    }
    else
    $uibModalInstance.close($ctrl.selected.item);
  };

Hope it helps :)

Working Plunker: https://plnkr.co/edit/70vdDsbFrSehaHR9TXNp?p=preview

The below code snippet demonstrates how form validation can be done. So since you have many fields you can validate each field with your desired validations.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>  
<body>

<h2>Validation Example</h2>

<form ng-app="myApp" ng-controller="validateCtrl" 
name="myForm" novalidate>

<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">Username is required.</span>
</span>
</p>

<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>

<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||  
myForm.email.$dirty && myForm.email.$invalid">
</p>

</form>

<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
    $scope.user = 'John Doe';
    $scope.email = '[email protected]';
});
</script>

</body>
</html>

1
On

Move the validate function into the $ctrl.ok() and remove it form the view.

$ctrl.ok = function () {
    if(!$ctrl.validate())
      $uibModalInstance.close($ctrl.selected.item);
    else
      return
  };

Here it is the working example: link