当使用select作为标签时,如何使用ng选项禁用angularjs中的选项

How do I disable options in angularjs with ng-options when using select as label

本文关键字:选项 何使用 ng angularjs select 标签      更新时间:2023-09-26

我在一个服务中有这些变量:

months: [
        { label: 'January', value: 1, disabled: true },
        { label: 'February', value: 2, disabled: true },
        { label: 'March', value: 3, disabled: true },
        { label: 'April', value: 4, disabled: false },
        { label: 'May', value: 5, disabled: false },
        { label: 'June', value: 6, disabled: false },
        { label: 'July', value: 7, disabled: false },
        { label: 'August', value: 8, disabled: false },
        { label: 'September', value: 9, disabled: false },
        { label: 'October', value: 10, disabled: false },
        { label: 'November', value: 11, disabled: false },
        { label: 'December', value: 12, disabled: false }
    ],
currentMonth: 4

我的选择是这样的:

<select name="goalStartMonth" id="goalStartMonth" class="form-control gb-select" ng-model="startMonth" ng-change="frequencyUpdated()" ng-options="month.value as month.label for month in months"></select>

这可以很好地构建<select>,但我想禁用当前月份之前的月份(不能选择过去的月份)

ng选项的角度文档显示:

"对数组中的值禁用时禁用标签"

所以我试过:

<select name="goalStartMonth" id="goalStartMonth" class="form-control gb-select" ng-model="startMonth" ng-change="frequencyUpdated()" ng-options="month.value as month.label disable when month.value < currentMonth for month in months"></select>

这会破坏<select>-不呈现任何选项。

我也试过:

<select name="goalStartMonth" id="goalStartMonth" class="form-control gb-select" ng-model="startMonth" ng-change="frequencyUpdated()" ng-options="month.label disable when month.value < currentMonth for month in months"></select>

同样的结果。

我在这里错过了什么?

一种方法是在<select>中的<option>上使用ng-repeatng-disabled,如下所示:

<select name="goalStartMonth" id="goalStartMonth" class="form-control gb-select" ng-model="startMonth" ng-change="frequencyUpdated()">
    <option ng-repeat="month in months" ng-disabled="month.value < currentMonth" >{{month.label}}</option>
</select>

在这里工作JSFiddle

编辑

如上所述,此功能直到1.4.0测试版才可用。这里有一个JSFiddle,显示它使用AngularJS 的1.4.0-beta.6版本

p>我想我知道为什么它不起作用。我查看了Angular文档中的ng选项文档,注意到他们有一个使用"数组中的值禁用时标签禁用"表示法的例子。

我试着在plnkr上的示例中从1.4.0-beta.6更改为1.3.15,但它不再有效。

这似乎是一个版本问题。

如果你检查https://github.com/angular/angular.js/issues/638您将看到这个禁用符号是最近添加的,因为这个问题已于2月18日关闭。

您可以在angular 1.4.1或以上中禁用ngOptions

HTML模板

<div ng-app="myapp">
<form ng-controller="ctrl">
    <select id="t1" ng-model="curval" ng-options='reportingType.code as reportingType.itemVal disable when reportingType.disable for reportingType in reportingOptions'>
        <option value="">Select Report Type</option>
    </select>
</form></div>

控制器代码


angular.module('myapp',[]).controller("ctrl", function($scope){
$scope.reportingOptions=[{'code':'text','itemVal':'TEXT','disable':false}, {'code':'csv','itemVal':'CSV','disable':true}, {'code':'pdf','itemVal':'PDF','disable':false}];})