0

所以我用 angularjs 创建动态表单。发送表单后,我将其从数组中删除。但是由于某些奇怪的原因,表单验证规则以某种方式“坚持”到下一个表单。例如。我发送第一个表格,如果第三个表格有有效答案,则第二个表格现在得到验证,依此类推,如果第 4 个表格有有效答案,则第 3 个表格将有效。这可能是什么原因?

这几乎是我所拥有的基础知识的精简代码

<div ng-repeat="item in ItemsAdder.items track by $index" ng-form="item.itemForm">
<div class="form-group control-group">
    <label for="category" class="col-sm-2 control-label">{{trans('adsAdd.category')}}</label>
    <select ng-options="category.name for category in categories track by category.id" ng-init="item.category=categories[0]" ng-model="item.category"></select>
</div>
<div class="form-group control-group" ng-class="{ 'has-error' : item.itemForm.price.$invalid && !item.itemForm.price.$pristine }">
    <label for="price" class="col-sm-2 control-label">Price</label>
    <input ng-model="item.price" ng-class="{ 'has-error' : item.itemForm.price.$invalid && !item.itemForm.price.$pristine }" required type="number" ng-trim="false" name="price">
    <p ng-show="item.itemForm.price.$error.number && !item.itemForm.price.$pristine" class="help-block">{{trans('items.add.priceNeedsToBeNumber')}}</p>
    <p ng-show="item.itemForm.price.$error.required && !item.itemForm.price.$pristine" class="help-block">{{trans('items.add.priceNeeded')}}</p>
</div>
<div class="form-group control-group" ng-class="{ 'has-error' : item.itemForm.description.$invalid && !item.itemForm.description.$pristine }">
    <label for="description" class="col-sm-2 control-label inputLabel">Description</label>
    <textarea ng-minlength="3" ng-class="{ 'has-error' : item.itemForm.description.$invalid && !item.itemForm.description.$pristine }" ng-model="item.description" name="description" required class="inputInput" style="max-width: 100%;"></textarea>
    <p ng-show="item.itemForm.description.$error.required && !item.itemForm.description.$pristine" class="help-block">{{trans('items.add.descriptionNeeded')}}</p>
</div>
<button ng-click="ItemsAdder.send($index)" ng-disabled="item.itemForm.$invalid">{{trans('adsAdd.send')}}</button>
</div>

还有我的发送功能:

ItemsAdderFactory.prototype.send = function ($index) {
                    var self = this;
                    var responsePromise = $http.post("",this.items[$index]);
                    responsePromise.success(function (data, status, headers, config) {
                        self.items.splice($index, 1);
                    });
                    responsePromise.error(function (data, status, headers, config) {
                        alert('There was an error, please try again.');
                    });
                };

顺便说一句,我将 ng-form="" 作为 item.ItemForm 所以我可以在按下发送所有按钮时通过项目访问表单,它会检查哪些表单是有效的并且只发送那些表单。如果有不同的或适当的方式来做这件事,我会全神贯注。

4

2 回答 2

0

所以,伙计们,我找到了答案。如果其他人得到这个,我会把它留在这里。问题是因为我在 ng-repeat 中使用了 $index 的跟踪,我猜想表单验证想要保留,因为索引没有改变。

因此,如果您遇到这些问题,请不要track by $index在 ng-repeat 中使用。

于 2015-06-11T14:28:42.927 回答
0

当您从数组中删除提交的内容时,ItemsAdder.items请记住 ng-repeat 有两种方式绑定,因此它会重置数组,现在第一个索引项成为第 0 个索引项。

这是对您面临的问题的最佳猜测。

于 2015-06-11T14:29:43.677 回答