Arkadiusz Kałkus
Arkadiusz Kałkus

Reputation: 18353

Angular validation messages don't work with ng-show and two inputs

I have implemented a form with a mode. Form can have 'Create' or 'Edit' mode. Depending on the mode it shows some div in one place of the layout or another. Div content is the same and it's input and some validation messages for it.

Here's simplified example.

View:

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
   <form name="editForm">
     <div ng-show='mode == "Edit"'>
       <div class="form-group" ng-class="{true:'has-error',false:''}[editForm.FirstName.$valid === false && editForm.FirstName.$dirty]">
          <input type="text" ng-model="foo" ng-maxlength="5" name="foo" required />
          <div class="help-block" ng-messages="editForm.foo.$error" ng-if="editForm.foo.$dirty">
            <p ng-message="required">Required</p>
            <p ng-message="maxlength">Too long</p>
          </div>
       </div>
     </div>
     <div ng-show='mode == "Create"'>
       <div class="form-group" ng-class="{true:'has-error',false:''}[edit.foo.$valid === false && edit.foo.$dirty]">
          <input type="text" ng-model="foo" ng-maxlength="5" name="foo" required />
          <div class="help-block" ng-messages="editForm.foo.$error" ng-if="editForm.foo.$dirty">
            <p ng-message="required">Required</p>
            <p ng-message="maxlength">Too long</p>
          </div>
       </div>
     </div>
   </form>
      <div>
      Mode: {{mode}} <br>
      Value: {{foo}} <br>
      Is form valid: {{editForm.foo.$valid}} <br>
      </div>
  </div>
</div>

Controller:

var myApp = angular.module('myApp',['ngMessages']);

myApp.controller('MyCtrl',function($scope){
    $scope.mode = 'Edit';
});

Here's JSFiddle with working example.

The problem is - validation messages work properly only when the last input is shown. In Edit mode - even if it's the same - messages don't show correctly.

Upvotes: 2

Views: 63

Answers (1)

Arkadiusz Kałkus
Arkadiusz Kałkus

Reputation: 18353

Instead of ng-show use ng-if directive.

ng-show causes browser to render both div elements, with ng-hide class on the element where ng-show expression is evaluated as false.

ng-if on the other hand causes div element to be not rendered if ng-if expression is false.

Upvotes: 1

Related Questions