javascript - 如何验证 angularjs 中的子属性?

标签 javascript validation angularjs

我有一个看起来像这样的模型:

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

我的表单名称是“bioValues[0].biometricValue, bioValues 1 .biometricValue”。

但是当我尝试验证我的表单时,不会触发我的字段验证错误上的“ng-show”。我查看了 Firebug 中的表单对象,当空但未触发 ng-show 时,我所有适用的表单错误都被正确标记为无效。

这是一个plunker .尝试将其中一个输入留空。 ng-show 上未触发所需的错误。

有什么想法吗?谢谢。

最佳答案

无需将要验证的字段命名为与要显示的模型完全相同的名称。

Here is a working plunker.

我所做的唯一更改是将模板中的字段命名为 bioValues1bioValues2

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

});

关于javascript - 如何验证 angularjs 中的子属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20749122/

相关文章:

javascript - 使用javascript在php页面上制作 'onClick'切换到php数组中的随机url

javascript - angular.module 和 window.angular.module 之间有什么区别吗?

javascript - 我想将这个结果查询放入 3 x 3 html 表中

angularjs - 如何将模板传递给属性中的指令?

javascript - 从 Angular Controller 动态地将脚本注入(inject)到 HTML

angularjs - 为什么 Angular Controller 中的绑定(bind)值不能立即可用

javascript - 简洁的 Angular 表单验证

c# - 具有可动态切换数据类型的文本框的 MVC 4 客户端验证

asp.net - 禁用验证器但验证器标注仍然显示并导致验证

javascript - 为什么我收到一个空的警报框?