额外选项和ng-required

时间:2014-09-19 22:46:24

标签: javascript angularjs

我使用此代码在我的选项列表中添加了一个额外选项:

var defaultOption = { id: 0, descrip: 'Select Item Tree...' };
$scope.metaData.itemTrees.splice(0, 0, defaultOption);

现在,在某些情况下我需要项目树,所以我有

<div class="col-lg-9">
    <select class="form-control" name="itemTree" id="itemTree"
            ng-model="currentSalespoint.iTreeTop" ng-required="salespointMode.needsItemTree"
            ng-options="t.id as t.descrip for t in metaData.itemTrees"></select>
</div>
<div class="field-validation-error">
    <span ng-show="editSalespointGeneral.itemTree.$error.required && editSalespointGeneral.itemTree.$dirty">Item Tree selection is required.</span>
</div>

问题是0不应该是有效的选择,例如我不能离开&#39;选择项目树&#39;作为选定的选项。我该怎么办才能真正做到这一点?

如果我尝试使用null而不是0,我会收到错误,但接着是&#39;选择..&#39;在我的下拉中消失,我有空行。

1 个答案:

答案 0 :(得分:1)

其中一个解决方案是直接在html中定义空项:

<select class="form-control" name="itemTree" id="itemTree"
        ng-model="currentSalespoint.iTreeTop" ng-required="salespointMode.needsItemTree"
        ng-options="t.id as t.descrip for t in metaData.itemTrees">
    <option value="">Select Item Tree...</option>
</select>

Plunker:http://plnkr.co/edit/7m8YYVz7HNs1OY7hRIF1?p=preview