如何禁用从Angular JS下拉列表中选择特定选项?

时间:2014-02-25 05:42:43

标签: javascript angularjs html-select

我想禁用AngularJS下拉列表中的特定选项。

它应该在下拉列表中列出,但不应该允许它被选中。所以我需要禁用它。

MyFile.tpl.html

<select class="form-control" ng-model="selectedFruits" 
        ng-options="fruit as fruit.name for fruit in fruits">
</select>

MyController.js

$scope.fruits = [{'name': 'apple', 'price': 100},{'name': 'guava', 'price': 30},
                 {'name': 'orange', 'price': 60},{'name': 'mango', 'price': 50},
                 {'name': 'banana', 'price': 45},{'name': 'cherry', 'price': 120}];

此处所有水果名称都应列在下拉列表中,但应禁用 mango cherry ,并且不应允许用户选择它。

有可能吗?如果可能的话,请告诉我解决方案。

2 个答案:

答案 0 :(得分:6)

使用select属性禁用了

disabled个选项。由于ng-options不支持停用,因此您必须在ng-repeat内生成选项,并根据要求设置ng-disabled

模板:

<select class="form-control" ng-model="selectedFruits">
    <option
        ng-repeat="fruit in fruits"
        ng-disabled="disabledFruits.indexOf(fruit.name) !== -1"
        ng-value="fruit">
         {{fruit.name}}
  </option>
</select>

内部控制器:

$scope.disabledFruits = ["mango", "cherry"]

JSBin

答案 1 :(得分:3)

刚刚遇到过这个问题,值得一提的是,从Angular 1.4.0-rc.1开始,这是可行的

这里是文档ngOptions

和一些对话Angular Github

HTML:

<!DOCTYPE html>
<html ng-app="testApp">

<head>
  <script src="https://code.angularjs.org/1.4.0-rc.1/angular.js"></script>
  <link href="style.css" rel="stylesheet" />
  <script src="script.js"></script>
</head>

<body ng-controller="testController">
  <select ng-model="myPerson" ng-options="person.name disable when person.isDisabled for person in people">
  </select>
</body>

</html>

JS:

var app = angular.module("testApp", []);

app.controller("testController", function($scope) {
  $scope.people = [{
    "id": "0",
    "name": "Homer",
    "surname": "Simpson",
    "isDisabled": false
  }, {
    "id": "1",
    "name": "Peter",
    "surname": "Griffin",
    "isDisabled": false
  }, {
    "id": "2",
    "name": "Philip",
    "surname": "Fry",
    "isDisabled": false
  }, {
    "id": "3",
    "name": "Humpty",
    "surname": "Dumpty",
    "isDisabled": true
  }, ];

  $scope.myPerson = $scope.people[2];
});

Plunker

如果您将禁用值设置为默认值,它将无效,您将看到空白的选定项目。