我有一个“自行车”数组,需要以我的表格填充(最小长度为1)。在我的控制器中,我有一个空数组'this.bikes = [];'
我有一些控件可以从阵列中添加和删除自行车。
addBike(bike){
this.bikes.push(bike);
this.currentBike = null;
}
removeBike(bike){
this.bikes = this.bikes.filter((b) => bike != b);
}
如何在数组本身上应用表单验证,以便在数组为空时我的表单显示为无效(类似于'if($(ctrl.bikes.length == 0)$ ctrl.form.bikes。$ valid =错误)?
<label for="bike-make-model">Enter make and model of bike</label>
<div class="input-group p-relative">
<input name="bikeMakeModel" type="text" ng-model="$ctrl.currentBike" class="form-control" id="bike-make-model">
<span class="input-group-btn ">
<button class="btn btn-default" ng-click="$ctrl.addBike($ctrl.currentBike)" ng-disabled="!$ctrl.currentBike">ADD</button>
</span>
</div>
</div>
<div class="list-group" ng-show="$ctrl.bikes.length > 0">
<ul>
<li class="list-group-item" ng-repeat="bike in $ctrl.bikes">
<span>{{bike}} </span>
<i ng-click="$ctrl.removeBike(bike)" class="pointer pull-right far fa-trash-alt"/>
</li>
</ul>
</div>
我想使用它来使用ng-disabled指令禁用我的提交按钮。
<button class="btn btn-primary" ng-disabled="!$ctrl.form.$valid" ng-click="$ctrl.continue()">Next</button>
答案 0 :(得分:0)
您尝试过
<button class="btn btn-primary" ng-disabled="!$ctrl.form.$valid || $ctrl.bikes.length==0" ng-click="$ctrl.continue()">Next</button>
或者您可以在脚本中添加一个变量以监视数组的长度。说
addBike(bike){
this.bikes.push(bike);
this.currentBike = null;
this.bikesArrayLength = this.bikes.length;
}
removeBike(bike){
this.bikes = this.bikes.filter((b) => bike != b);
this.bikesArrayLength = this.bikes.length;
}
并在您的按钮中执行
<button class="btn btn-primary" ng-disabled="!$ctrl.form.$valid || $ctrl.bikesArrayLength==0" ng-click="$ctrl.continue()">Next</button>
答案 1 :(得分:0)
您可以为此使用directive
。使directive
并在link函数中定义逻辑,如果数组为空会使表单无效并且不提交,则您的代码很短,这就是为什么,我不能为您做。
这是解决问题的有角度的方法。我现在所能做的就是提供逻辑或让您知道这将如何下降。
.directive("dirName",function(){
return {
require: "ngModel",
scope: {
confirmArrayLength: "="
},
link: function(scope, element, attributes, modelVal) {
modelVal.$validators.dirName= function(val) {
return "your logic to check if array is empty or not!"
};
// and $watch function will validate and invalidate on the basis of return value of above function
scope.$watch("confirmArrayLength", function() {
modelVal.$validate();
});
}//link ends here
};//return ends here})
如果这是您的问题的解决方案,请接受此答案,以便可以关闭该线程,谢谢。如果您需要任何进一步的帮助,请随时询问。