【问题标题】:How to validate select elements using AngularJS如何使用 AngularJS 验证选择元素
【发布时间】:2014-10-20 12:16:06
【问题描述】:

我的页面上有以下 HTML,其中有 2 个 select 元素。我希望它们都是必需的。我希望第二个元素 currentModel 保持禁用状态,直到使用除 Year 以外的值选择第一个元素,这是我的默认值。

<select class="form-control  input-xsmall select-inline" data-ng-model="currentYear" >
    <option>Year</option>
    <option ng-repeat="year in years" value="{{year}}">{{year}}</option>
</select>
<select  class="form-control  input-xsmall select-inline" data-ng-model="currentModel">
    <option>Model</option>
    <option ng-repeat="model in models" value="{{model.niceName}}">{{model.name}}</option>
</select>

有人可以帮助我如何验证这样的选择元素吗?

【问题讨论】:

    标签: html angularjs select angularjs-validation


    【解决方案1】:

    您只需要使用 ng-model 和 ng-options,而不是通过 ng-repeat 手动创建选项。让 Angular 为您创建选项。

    <select class="form-control  input-xsmall select-inline" data-ng-model="currentYear"
              ng-options="year for year in years track by year">
        <option value="">Year</option>
    </select>
    
    <select  class="form-control  input-xsmall select-inline" data-ng-model="currentModel" 
       ng-disabled="!currentYear" 
       ng-options ="model.niceName as model.name for model in models track by model.niceName">
        <option value="">Model</option>
    </select>
    

    Plnkr

    • ng-options="year for year in years track by year" 遵循语法label for value in array

    • ng-options ="model.niceName as model.name for model in models track by model.niceName" 遵循语法select as label for value in array

    • 只需为两个选择设置ng-model。对于模型,因为我使用了 select as 语法 (model.niceName as model.name),currentModel 将具有所选项目的 niceName 属性。如果您从模型中删除 select as 部分,它将具有相应的模型对象。

    • 根据 currentModel 的值在第二次选择时设置 ng-disabled

    由于 ng-select 在处理对象时存在跟踪错误,我们需要使用 as 语法

    【讨论】:

    • 非常感谢 PSL,就像一个魅力 :)。还有一件事,我希望它们都是表单中的必填字段,但我不太能做到。
    • 刚刚意识到当为currentModel 选择一个值时,该下拉列表的默认值(即Model)不会改变。
    【解决方案2】:

    ng-disabled="currentYear == -1" 通过 $scope.currentYear = -1 选择默认值 如果 currentYear 模型值为 '-1',这将禁用第二个选择框

    <select class="form-control  input-xsmall select-inline" data-ng-model="currentYear" >
        <option value="-1">Year</option>
        <option ng-repeat="year in years" value="{{year}}">{{year}}</option>
    </select>
    <select  class="form-control  input-xsmall select-inline" data-ng-model="currentModel"
        ng-disabled="currentYear == 'Year'">
        <option>Model</option>
        <option ng-repeat="model in models" value="{{model.niceName}}">{{model.name}}</option>
    </select>
    

    这里是 Plunkr 示例:http://plnkr.co/edit/LIAqMq4TEz9xOCUGPAUs?p=preview

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多