2015-01-06 19 views
0

我創建了一個動態表單,其中有作爲數組提交的重複字段。但是,我想分別驗證每個字段並在其旁邊顯示錯誤消息。如果我只有一行,它工作正常,但一旦我添加第二行,第一行停止顯示錯誤。如何在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 
    }; 

    } 
]); 

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

我能滿足於不具有它旁邊的每個字段,只要改變對其他字段集不其中正確觸發錯誤消息我可以在頂部彈出它。我看到的主要問題是,因爲它們是末尾傳遞給表單的數組0123¾,它們將無法正常工作。

表單驗證時提交按鈕被禁用,所以我不知道爲什麼消息只鎖定到最後一行添加。

回答

3

使用子窗體來分隔範圍。

​​
+0

這似乎工作。但是,如果存在其他嵌套標記(如果表單位於單元格之間,則表示爲​​),它將不起作用。我必須把它放在具體輸入的範圍內。你知道爲什麼這是如何讓它更連續一些? – roloenusa

+0

ng形式可以作爲這些情況下的一個屬性。 – Karthik

相關問題