trevorc
trevorc

Reputation: 3031

How do I validate child properties in angularjs?

I have model that looks like this:

$scope.item = {
    userId: 2,
    bioValues: [{
      name: 'Systolic',
      biometricValue: 120
    }, {
      name: 'Diastolic',
      biometricValue: 80
    }]
  };

My form names are "bioValues[0].biometricValue, bioValues1.biometricValue".

But when I try and validate my form, 'ng-show' on my field validation errors isn't triggered. I have looked at the form object in firebug and all of my applicable form errors are correctly marked as invalid when empty but ng-show isn't triggered.

Here is a plunker. Try leaving one of the inputs empty. The required error is not triggered on ng-show.

Any ideas? Thanks.

Upvotes: 3

Views: 95

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67316

There is no need to name the fields you are validating the exact name as the model that you are displaying.

Here is a working plunker.

The only change that I made was to name the fields in the template bioValues1 and bioValues2.

HTML:

<body ng-controller="MyCtrl">
  <form novalidate name="form">
    <div class="row">
      <input type="text" name="bioValues1" ng-model="item.bioValues[0].biometricValue" required />
      <span class="error" ng-show="form.bioValues1.$error.required">*Required</span>
    </div>
    <div class="row">
      <input type="text" name="bioValues2" ng-model="item.bioValues[1].biometricValue" required />
      <span class="error" ng-show="form.bioValues2.$error.required">*Required</span>
    </div>
  </form>
</body>

JS:

var myApp = angular.module("MyApp", []);

myApp.controller("MyCtrl", function($scope) {
  $scope.item = {
    userId: 2,
    bioValues: [{
      name: 'Systolic',
      biometricValue: 120
    }, {
      name: 'Diastolic',
      biometricValue: 80
    }]
  };

});

Upvotes: 4

Related Questions