angularjs - проверка внутри ng-repeat для атрибутов имен с массивами
Я работаю над проектом, который использует ASP.NET MVC 5 на стороне сервера. Как упоминалось в этом посте, моя форма на стороне сервера принимает массив объектов в качестве параметра. Поэтому мне нужно создать name
атрибуты на мой взгляд, как это.
QualificationList[0].Degree
QualificationList[0].Institute
QualificationList[1].Degree
QualificationList[1].Institute
QualificationList[2].Degree
QualificationList[2].Institute
.
.
.
.
QualificationList[n].Degree
QualificationList[n].Institute
Обратите внимание, что это не дублированный вопрос, так как я перепробовал практически все решения от Stackru и других сайтов. Этот случай немного другой (и сложный тоже). Вот n
не является фиксированным значением. С помощью ng-repeat
это то, как я это делаю, и это прекрасно работает.
<div ng-form="myForm" class="form-group" ng-repeat="q in QualificationList">
<div class="col-md-9">
<input class="form-control text-box single-line" ng-model="QualificationList[$index].Degree" ng-required="true" name="QualificationList[{{$index}}].Degree" type="text" value="" />
<span ng-show="QualificationList[$index].Degree.$invalid">The Degree field is required</span>
</div>
<div class="col-md-3">
<input class="form-control text-box single-line" ng-model="QualificationList[$index].Institute" ng-required="true" name="QualificationList[{{$index}}].Institute" type="text" value="" />
<span ng-show="QualificationList[$index].Institute.$invalid">The Institute field is required</span>
</div>
</div>
И, как показано выше, я хочу проверить значения, введенные (для степени и института) пользователем. Я пробовал это решение также, но оно не работает.
Что я могу сделать, чтобы показать ошибки проверки? Обратите внимание, что для уменьшения сложности, я упомяну только два поля, а именно Degree
а также Institute
, В моем живом проекте более 20 полей, которые требуют разных видов проверок (например, ng-pattern, email и т. Д.)
Для простоты я создал скрипку здесь: http://jsfiddle.net/wa5y5L15/29/
1 ответ
Вы используете ngForm для каждого элемента списка, который подходит для индивидуальной проверки, но вы не можете назвать и ссылаться на входные данные, подобные этому.
Поскольку область действия каждой ngForm изолирована, просто используйте простое имя, например, Degree или Institute (и не забудьте добавить в качестве префикса имя формы в выражении ng-show):
<div ng-form="myForm" class="form-group" ng-repeat="q in QualificationList">
<div class="col-md-9">
<input class="form-control text-box single-line" ng-model="QualificationList[$index].Degree" ng-required="true" name="Degree" type="text" value="" />
<span ng-show="myForm.Degree.$invalid">The Degree field is required</span>
</div>
<div class="col-md-3">
<input class="form-control text-box single-line" ng-model="QualificationList[$index].Institute" ng-required="true" name="Institute" type="text" value="" />
<span ng-show="myForm.Institute.$invalid">The Institute field is required</span>
</div>
</div>
Кстати, вот хорошая статья:
http://scotch.io/tutorials/building-dynamic-angular-forms-with-ngrepeat-and-ngform
РЕДАКТИРОВАТЬ:
Хорошо понял. Я думаю, что вы не можете использовать модель формы с этим. Но вы можете проверить свойства в области видимости контроллера с помощью регулярного выражения (и поместить его в ваш ngShow). Если вам просто нужна непустая строка, используйте sth вот так:
<div ng-form="myForm" class="form-group" ng-repeat="q in QualificationList">
<div class="col-md-10 col-xs-10">
<div class="col-md-6 col-xs-6">
<input class="form-control text-box single-line" ng-model="QualificationList[$index].Degree" ng-required="true" name="QualificationList[{{$index}}].Degree" type="text" value="" />
<span ng-show="!QualificationList[$index].Degree">The Institute field is required</span>
</div>
<div class="col-md-6 col-xs-6">
<input class="form-control text-box single-line" ng-model="QualificationList[$index].Institute" ng-required="true" name="QualificationList[{{$index}}].Institute" type="text" value="" />
<span ng-show="!QualificationList[$index].Institute">The Institute field is required</span>
</div>
</div>
</div>