我正在使用angularjs和$invalid
将.has-error
添加到我的表单组。问题是我的表单组之一有多个输入,并排...
<div class="form-group">
<div class="col-sm-6">
<label for="location">Location</label>
<select class="form-control input-lg" name="location" ng-model="newRack.location" ng-options="location as location.name for location in locations" placeholder="Locations" required></select>
</div>
<div class="col-sm-6">
<label for="name">Rack Size</label>
<input type="number" class="form-control input-lg" name="size" ng-model="newRack.size" min="1" max="48" required>
</div>
</div>
验证看起来与此类似,但也包括对size元素的其他验证。
ng-class="{ 'has-error': rackForm.location.$invalid && rackForm.location.$dirty }"
如果name=size
变为无效,则表示.has-error
应用于整个表单组,这可能会让最终用户感到困惑。有没有办法
答案 0 :(得分:1)
我这样做的方法是为每个输入元素创建表单组。此外,我相信您不需要内部<div class="col-sm-6">
,因为您可以使用form-group加入该类并获得相同的结果。
<div class="form-group col-sm-6" ng-class="{ 'has-error': rackForm.location.$invalid && rackForm.location.$dirty }">
<label for="location">Location</label>
<select class="form-control input-lg" name="location" ng-model="newRack.location" ng-options="location as location.name for location in locations" placeholder="Locations" required></select>
</div>
<div class="form-group col-sm-6" ng-class="{ 'has-error': rackForm.size.$invalid && rackForm.size.$dirty }">
<label for="name">Rack Size</label>
<input type="number" class="form-control input-lg" name="size" ng-model="newRack.size" min="1" max="48" required>
</div>
如果有帮助,请告诉我
答案 1 :(得分:0)
简单的答案是你试图在HTML中添加太多逻辑。查看创建Angular指令,在幕后实现您的逻辑或在控制器中执行,并设置您尝试检查scope
的状态。
Angular的一个关键原则是不在HTML中放置逻辑。
答案 2 :(得分:0)
要在不更改布局的情况下执行此操作,只需在ng-class
类的每个div中使用col
sintax。像那样:
<div class="form-group">
<div class="col-sm-6" ng-class="{ 'has-error': rackForm.location.$invalid && rackForm.location.$dirty }">
<label for="location">Location</label>
<select class="form-control input-lg" name="location" ng-model="newRack.location" ng-options="location as location.name for location in locations" placeholder="Locations" required></select>
</div>
<div class="col-sm-6" ng-class="{ 'has-error': rackForm.size.$invalid && rackForm.size.$dirty }">
<label for="name">Rack Size</label>
<input type="number" class="form-control input-lg" name="size" ng-model="newRack.size" min="1" max="48" required>
</div>
</div>