我无法从来自ng-repeat的字段进行验证。一旦我满足错误,每个具有相同的字段都满足。有没有其他方法可以做到这一点?比如使用ng-model作为验证指标而不是名称?
这是我的代码:
HTML
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
<form name="myForm" novalidate >
<fieldset data-ng-repeat="choice in choices">
<input type="text" ng-model="choice.name" name="fieldname" placeholder="Enter mobile number" required>
<span ng-hide="!myForm.fieldname.$error.required">THIS FIELD IS REQUIRED {{ myForm.fieldname.$error.required }}</span>
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ choices }}
</div>
</div>
JS
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}, {id: 'choice2'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
PS。
我知道这可以通过使用incremental来操作输入的name属性来完成,但我想知道是否可以用更少的工作来完成
答案 0 :(得分:2)
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
<form name="myForm" novalidate >
<fieldset data-ng-repeat="choice in choices" data-ng-form="nestedMyForm" >
<input type="text" ng-model="choice.name" name="fieldname" placeholder="Enter mobile number" required>
<span ng-hide="!nestedMyForm.fieldname.$error.required">THIS FIELD IS REQUIRED {{ nestedMyForm.fieldname.$error.required }}</span>
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ choices }}
</div>
</div>
检查我如何添加数据-ng-form =“nestedMyForm”希望它能够正常工作
答案 1 :(得分:0)
如果不在名称字段上添加增量,我认为你不能这样做。 您可以使用
之类的内容轻松完成<input type="text" ng-model="choice.name" name="fieldname_{{$index}}" required>
答案 2 :(得分:0)
这应该做的伎俩 - 请注意我如何将字段名称更改为 - field + $ index,以便我们可以在ng-repeat中的每次迭代之间区分
<div ng-app="angularjs-starter" ng-controller="MainCtrl"> <form name="myForm" novalidate > <fieldset data-ng-repeat="choice in choices">
<input type="text" ng-model="choice.name" ng-init="vm.name='field'+$index" name="{{vm.name}}" placeholder="Enter mobile number" required>
<span ng-hide="!myForm.{{vm.name}}.$error.required">THIS FIELD IS REQUIRED {{ myForm.{{vm.name}}.$error.required }}</span>
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button> </fieldset> <button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ choices }} </div> </div>