如何验证模型中的列表是否至少包含一个元素?

时间:2017-11-03 13:01:24

标签: angularjs

在我的Angular 1.6代码中,我有类似的东西:

<div class="house" ng-repeat="house in $ctrl.houses" ng-form="houseForm">
  <div class="room" ng-repeat="room in house.rooms" ng-form="roomForm">
    <div class="item" ng-repeat="item in room.items" ng-form="itemForm">
      <input ng-repeat="question in item.questions" ng-required="true" />
    </div>
  </div>
</div>

然后我使用ng-invalid CSS类来设置无效输入和无效部分的样式。现在我有一个新的要求,我需要考虑一个没有元素的段(例如没有项目的房间)作为无效,并给它相同的样式,就好像它包含一个无效的输入。

我试图使用像这样的隐藏输入来破解它

<input type="number" disabled ng-model="room.Items.length" ng-required="true" min="1" style="display:none"/> 

哪个有效,但在页面加载时给了我一个Javascript错误。它也不是很干净。解决这个问题的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

你可以尝试类似下面的代码吗?

<div class="house" ng-repeat="house in $ctrl.houses" ng-form="houseForm">
  <div class="room" ng-repeat="room in house.rooms" ng-form="roomForm">
    <div class="item" ng-repeat="item in room.items" ng-form="itemForm">
      <input ng-repeat="question in item.questions" ng-required="true" />
    </div>
    <div class="item" ng-if="!room.items">
      <input ng-model="room.Items" minlength="1" ng-required="true" />
    </div>
  </div>
</div>

答案 1 :(得分:0)

Immanuel Kirubaharan S的答案很接近,但在所有情况下均无效。这个小修改确实有效。

<div class="house" ng-repeat="house in $ctrl.houses" ng-form="houseForm">
  <div class="room" ng-repeat="room in house.rooms" ng-form="roomForm">
    <div class="item" ng-repeat="item in room.items" ng-form="itemForm">
      <input ng-repeat="question in item.questions" ng-required="true" />
    </div>
    <div class="item" ng-if="!room.items">
      <input ng-model="room.Items[0]" ng-required="true" />
    </div>
  </div>
</div>