简体   繁体   中英

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, bioValues 1 .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.

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
    }]
  };

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM