qiushibaike
qiushibaike

Reputation: 21

How to disable dropdown list item in AngularJS?

I am a beginner to AngularJS and I am making a web app that needs to disable exiting values in a dropdown list.

I know how to do it in jQuery. It is just like this: http://jsfiddle.net/qiushibaike/FcLLn/

But I don't really know how to do it in AngularJS, Should I try to disable the item or hide it? Can I set a value

HTML

<select ng-model="numbers.value" required>
     <option ng-repeat="item in items"> {{item.name}} </option>
</select><br/>

JavaScript

$scope.numbers= {};

$scope.items = [
    { id: 1, name: '11111'},
    { id: 2, name: '22222'},
    { id: 3, name: '33333'}
];

If I have something like this, how can I disable or hide the option 2 and 3 by AngularJS like what I did by using jQuery?

Upvotes: 1

Views: 17704

Answers (2)

Pallav Gupta
Pallav Gupta

Reputation: 21

This is also possible with ngOptions.

You just need to add "disable when" in your ng-options tag.

In your case, you can also do like this

HTML

    <select ng-model="numbers.value" 
    ng-options="var.name as var.name disable when var.disabled for var in items" required>
      <option value="">-- Select --</option></select>

Javascript

$scope.items = [
    { id: 1, name: '11111'},
    { id: 2, name: '22222', disabled: true },
    { id: 3, name: '33333', disabled: true }
]

Plunkr

If you want to disable any option dynamically from your code,

here is a Plunkr : Dynamic Example.

Upvotes: 2

dutzi
dutzi

Reputation: 1928

Use Angular's ngDisabled directive.

HTML

<select ng-model="numbers.value" required>
    <option ng-repeat="item in items" ng-disabled="item.disabled"> {{item.name}} </option>
</select>

Javascript

$scope.items = [
    { id: 1, name: '11111'},
    { id: 2, name: '22222', disabled: true },
    { id: 3, name: '33333', disabled: true }
]

Upvotes: 0

Related Questions