簡體   English   中英

如何在AngularJS中顯示數組表單字段的驗證錯誤?

[英]How to display validation errors for array form fields in AngularJS?

我創建了一個動態表單,其中重復的字段作為數組提交。 但是,我想分別驗證每個字段並在其旁邊顯示錯誤消息。 如果我只有一行,則可以正常工作,但是一旦添加第二行,第一行就會停止顯示錯誤。

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

  }
]);

朋克: http ://plnkr.co/edit/Fyqmg2AlQLciAiQn1gxY

我可以滿足於在每個字段旁邊都沒有它,只要對其他字段集所做的更改確實觸發了錯誤消息,在這種情況下,我可以將其彈出到頂部。 我看到的主要問題是,因為它們是數組codes[] ,它們最終傳遞到表單,所以它們將無法正常工作。

表單驗證時已正確禁用了“提交”按鈕,因此我不確定為什么消息僅鎖定到添加的最后一行。

使用子窗體來分隔范圍。

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM