How can I disable to select the particular option from Angular JS dropdown?

只愿长相守 提交于 2019-12-01 19:18:22

问题


I want to disable a particular option from AngularJS dropdown.

It should be listed in the dropdown but should not allow it to be selected. So i need to disable it.

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}];

Here all the fruit names should be listed in the dropdown but mango and cherry should be disabled and should not allow the user to select it.

Is it possible? If possible, please let me know the solution please.


回答1:


select options are disabled with disabled attribute. Since ng-options doesn't support disabling, you'll have to generate options within ng-repeat and set ng-disabled based on requirements.

Template:

<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>

Inside controller:

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

JSBin.




回答2:


Just came across this and it worth mentioning that this is possible as of Angular version 1.4.0-rc.1

here are docs ngOptions

and some conversations 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];
});

and Plunker

If you set disabled value as default it wont work and you will see blank selected item instead.



来源:https://stackoverflow.com/questions/22005601/how-can-i-disable-to-select-the-particular-option-from-angular-js-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!