Form error not displayed using $error, $invalid

Issue

I’m trying to replicate an example in ng-book jsbin.

Here is my plnkr

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.fields = [{placeholder: 'Email', isRequired: true},
               {placeholder: 'Password', isRequired: true},
               {placeholder: 'Comment(Optional)', isRequired: false}]
  $scope.formSubmit = function(){
    for (var i=0; i < $scope.fields.length; i++)
    { var obj = $scope.fields[i] 
      for (var key in obj){
        if(obj.hasOwnProperty(key)){
          alert(key + ' : ' + obj[key])
        }
      }
    }
  }                 
});

html

<html ng-app="plunker">

  <head><script data-require="angular.js@1.2.x"     src="https://code.angularjs.org/1.2.22/angular.js" data-semver="1.2.22"></script>
<script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <form name='main_form' ng-submit='formSubmit()' novalidate>
  <div ng-repeat="field in fields" ng-form="dynamic_form">
    <input type='text'
           name='dynamic_input'
           ng-required='field.isRequired'
           ng-model='field.name'
           placeholder='{{field.placeholder}}'>
        <div ng-show="dynamic_form.dynamic_input.$dirty && dynamic_form.dynamic_input.$invalid">
          <span ng-show="dynamic_form.dynamic_input.$error.required"> This field is required.</span>
        </div> 
      </div>
      <button type='submit' ng-diabled="main_form.$pristine && main_form.$invalid">Submit     All</button>
    </form>
  </body>

</html>

Issues I’m facing here:

  1. submit button is not disabled
  2. Error for required field are not being shown.
  3. If I click on submit, I’m getting $hash key as well in alert. Why is that?

Thanks.

Solution

1)submit button is not disabled

You have a typo it must be ng-disabled. Also change your condition to disable it when invalid :-

 <button type='submit' ng-disabled="main_form.$invalid">Submit All</button>

2)Error for required field are not being shown.

It will now show up when you remove the typed in value

3)If I click on submit, I’m getting $hash key as well in alert. Why is that?

Angular adds a unique key ($$hashkey) to keep track of the repeated items. If you specify a track by in your ng-repeat (which must be a unique key) it won’t add it. In your case since there is no id or anything associated you could use $index. (In the demo i have added an id property and used that to track by)

ng-repeat="field in fields track by $index"

Demo

Answered By – PSL

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.