Thomas Zoé Thomas Zoé - 3 months ago 33
AngularJS Question

AngularJS 1.5.6 reset form & ng-messages

I read some Stackoverflow posts how to reset a form, but I doesn't get it.
The input was valid but the error message was shown. Debugging the application shows me that the message gets a style="opacity: 1;margin-top: 0px;", but I have no idea from where.

<md-input-container flex style="margin-top: 0;margin-bottom: 5px">
<label translate>maintenanceMessage.description</label>
<input md-maxlength="40" required name="description" md-no-asterisk
ng-model="maintenanceMessageCtrl.newMaintenanceMessage.description" flex>
<div ng-messages="maintenanceMessageForm.description.$error" ng-if="maintenanceMessageForm.description.$touched">
<div ng-message="required" translate>maintenanceMessage.description.requiredMessage</div>
<div ng-message="md-maxlength" translate>maintenanceMessage.description.maxLengthMessage</div>
</div>
</md-input-container>


on reset I execute following function

ctrl.resetFormAndHideDialog = function () {
ctrl.newMaintenanceMessage = {};
ctrl.newMaintenanceMessage.expirationDate = new Date();
ctrl.showLastModification = false;
$scope.maintenanceMessageForm.$setUntouched();
$scope.maintenanceMessageForm.$setPristine();
$mdDialog.hide();
};


Am I missing something?

Thanks for helping.




Conclusio:
It seems that angular material 1.1.1 has a bug. So ng-message wasn't hidden.

Answer

I've put your relevant markup and code into a CodePen and it seems fine - CodePen

The only odd thing is that the character count does not get set to 0 on form reset. Maybe a bug.

Markup

<div ng-controller="AppCtrl" ng-cloak="" ng-app="MyApp">
   <form name="maintenanceMessageForm">
    <md-input-container flex style="margin-top: 0;margin-bottom: 5px">
      <label>maintenanceMessage.description</label>
      <input md-maxlength="40" required name="description" md-no-asterisk ng-model="newMaintenanceMessage.description" flex>
      <div ng-messages="maintenanceMessageForm.description.$error" ng-if="maintenanceMessageForm.description.$touched">
        <div ng-message="required">{{maintenanceMessage.description.requiredMessage}}</div>
        <div ng-message="md-maxlength">{{maintenanceMessage.description.maxLengthMessage</div>
      </div>
    </md-input-container>
  </form>
  <md-button class="md-raised md-primary" ng-click="resetForm()">Reset</md-button>
</div>

JS

angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache', 'ngDialog'])

.controller('AppCtrl', function($scope) {
  $scope.maintenanceMessage = {
    description: {
      requiredMessage: "This is required",
      maxLengthMessage: "Max length is 40"
    }
  };

  $scope.resetForm = function () {
    $scope.newMaintenanceMessage = {};
    $scope.maintenanceMessageForm.$setUntouched();
    $scope.maintenanceMessageForm.$setPristine();
  };
});