如何在AngularJS中显示数组表单字段的验证错误?

时间:2015-01-06 19:27:38

标签: javascript angularjs forms

我创建了一个动态表单,其中重复字段作为数组提交。但是,我想单独验证每个字段并在其旁边显示错误消息。如果我只有一行,它工作正常,但一旦我添加第二行,第一行停止显示错误。

<form name='user' id='user' novalidate>
    <div ng-repeat="bonus in bonuses">
        <input name='codes[]' ng-model="bonus.code" lower-than="{{bonus.end_code}}" />
        <input name='end_codes[]' ng-model="bonus.end_code" />
        <span class="text-error" ng-show="user['codes[]'].$error.lowerThan">
            Code must be less than End Code.
        </span>
    </div>
</form>

AngularJS

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

app.controller('NewBonusController', function($scope) {
    $scope.bonuses = [];

    $scope.addFields = function () {
      $scope.bonuses.push({code:'', end_code: ''});
    }

    $scope.submit = function(){
        console.log($scope.bonuses);
    }
});


// Validate that one field is less or equal than other.
app.directive('lowerThan', [
  function() {

    var link = function($scope, $element, $attrs, ctrl) {

      var validate = function(viewValue) {
        var comparisonModel = $attrs.lowerThan;

        if(!viewValue || !comparisonModel){
          // It's valid because we have nothing to compare against
          ctrl.$setValidity('lowerThan', true);
        }

        // It's valid if model is lower than the model we're comparing against
        ctrl.$setValidity('lowerThan', viewValue <= comparisonModel );
        return viewValue;
      };

      ctrl.$parsers.unshift(validate);
      ctrl.$formatters.push(validate);

      $attrs.$observe('lowerThan', function(comparisonModel){
        return validate(ctrl.$viewValue);
      });

    };

    return {
      require: 'ngModel',
      link: link
    };

  }
]);

plunker:http://plnkr.co/edit/Fyqmg2AlQLciAiQn1gxY

我可以满足于在每个字段旁边没有它,只要对其他字段集的更改确实正确地触发错误消息,在这种情况下我可以将其弹出顶部。我看到的主要问题是因为它们是最后传递给表单的数组codes[],它们将无法正常工作。

在表单验证时正确禁用了提交按钮,因此我不确定为什么消息只锁定到添加的最后一行。

1 个答案:

答案 0 :(得分:3)

使用子表格分隔范围。

<ng-form name="frmChild">
  <input name='codes' ng-model="bonus.code" lower-than="{{bonus.end_code}}" />
  <input name='end_codes' ng-model="bonus.end_code" />
  <span class="text-error" ng-show="frmChild.codes.$error.lowerThan">
    Code must be less than End Code.
  </span>
</ng-form>