如何使用AngularJs禁用ng选项中的选项

How to disabled option from ng-options using AngularJs?

本文关键字:选项 ng 禁用 何使用 AngularJs      更新时间:2023-09-26

当用户打开模式窗口时,我正在调用rest服务,以获得下面代码中的布尔标志data,现在如果该标志为true,我想禁用ng选项中的选项,其中id为RA_ATTST_LANGUAGE。如何根据以下逻辑禁用下拉选项?

main.html

<select name="adminNotificationTypeCode" class="form-control" ng-model="messageNotificationDTO.adminNotificationTypeCode" required id="adminNotificationTypeCode" ng-change="attestationCheck()" ng-options="adminDataSource.id as adminDataSource.text disable when adminDataSource.id == 'RA_ATTST_LANGUAGE' && disableRA_ATTST_LANGUAGE for adminDataSource in adminDataSource">
                            <option value="">Select...</option>
                        </select>

main.js

function getAttestationLanValidation (){
          MessageAdminNotificationFactory.getAttestationLanValidation().then(function(response){
            if(response){
              $scope.disableRA_ATTST_LANGUAGE = response.data;
            }
          });
        };
           //Add new Notification
           $scope.addMessageNotification = function() {
               $scope.messageNotificationModal.open().center();
               $scope.clearNotificationForm();
               getAttestationLanValidation();
           };

dropdown.json

[{
    "uid": null,
    "index": 0,
    "selected": null,
    "expanded": null,
    "id": "RA_PLTFRM_NOTIF",
    "text": "Platform Maintenance Notification",
    "parentId": null,
    "items": null
}, {
    "uid": null,
    "index": 0,
    "selected": null,
    "expanded": null,
    "id": "RA_ATTST_LANGUAGE",
    "text": "Attestation Language",
    "parentId": null,
    "items": null
}]

*由于的进一步解释而编辑

尝试将你的ng选项属性更新为:

 ng-options="adminDataSource.id as adminDataSource.text disable when adminDataSource.id == 'RA_ATTST_LANGUAGE' && disableRA_ATTST_LANGUAGE for adminDataSource in adminDataSource"

您将希望为您的作用域创建一个布尔成员,根据其余结果将其设置为true或false。。我称之为$scope.disableRA_ATTST_LANGUAGE

演示的Plunker

假设代码中的其他一切都是正确的,并且您的服务在dropdown.json中对每个实例进行一次调用;如果您只需要知道数据是否存在,而不需要获取实际的数据内容,那么一种快速而肮脏的方法是将名称存储在数组中,并使用ng-disabled指令检查该数组中是否存在id。您的变量名称令人困惑,所以我只是将它们通用化,并将您选择的选项的源数组称为"items"

你的js需要这样的

 // create an empty array when initializing
    $scope.thatArrayOfIdsThatHaveData = [];
    function getAttestationLanValidation() {
      MessageAdminNotificationFactory.getAttestationLanValidation()
          .then(function(response) {
            var data = response.data;
            console.log('attestation', data);
            if (data) {
              thatArrayOfIdsThatHaveData.push(id);
            }
      });
    };

在你的模板中有这样的东西:

<select ng-model="messageNotificationDTO.adminNotificationTypeCode"
        ng-change="attestationCheck()">
  <option value="">Select...</option>
  <option ng-repeat="item in items" 
          value="item.id"
          ng-disabled="thatArrayOfIdsThatHaveData.indexOf(item.id)>=0">{{ item.label }}</option> 
</select>