11

Is it possible to hide select box options using the ng-hide directive?

http://jsfiddle.net/cr4UB/

<div ng-app ng-controller="Controller">
    <select ng-model="myDropDown">
          <option value="one">One</option>
          <option value="two" ng-hide="myDropDown=='one'">Two</option>
          <option value="three">Three</option>
    </select>

    {{myDropDown}}
</div>
ThinkingInBits
  • 10,792
  • 8
  • 57
  • 82
  • What version of AngularJS are you using, and are you locked into that version? – André Dion Sep 09 '13 at 16:33
  • Using version 1.2. Thanks Chandermani and Andre, both were good answers, but Chandermani's solution is the more simple path for what I'm after. Upvotes for all though :) – ThinkingInBits Sep 09 '13 at 17:10

2 Answers2

18

AngularJS 1.1.5 has a directive ng-if which can work for you. Check this fiddle http://jsfiddle.net/cmyworld/bgsVw/

Chandermani
  • 42,589
  • 12
  • 85
  • 88
  • but what happens when you select option two, it seems to not appear in the dropdown – David Chase Sep 09 '13 at 16:34
  • `ng-if` shows the content if the condition is evaluated to true. You need to write condition accordingly. – Chandermani Sep 09 '13 at 16:36
  • @DavidChase i don't know, the context of when to hide or not, so i just took original example and replaced ng-hide with ng-if. ng-hide and ng-show only add some class to html.Whereas ng-if manipulates the DOM. – Chandermani Sep 09 '13 at 16:38
  • i understand your logic, but doesnt your solution pose another problem? – David Chase Sep 09 '13 at 16:43
  • I did not get the problem you are mentioning. – Chandermani Sep 09 '13 at 17:00
  • @DavidChase You would just need to change the `ng-if` condition to `ng-if="myDropDown!='one'"` to fulfill OP's example using Chandermani's solution. – André Dion Sep 09 '13 at 17:12
  • `ng-if` did the trick. If you use `ng-hide` or `ng-show`.. it was working fine on chrome.. but IE was still displaying the option even if the condition was truthy to hide it. – Abdel Raoof Olakara Jun 22 '15 at 05:34
2

I couldn't get it to work using ng-hide to check the value of your ng-model (likely some race-condition with reading/writing to the same model at once), however, I did come up with a working example of the functionality you're after:

View markup

<div ng-app ng-controller="Controller">
    <select ng-model="selectedOption" ng-options="o for o in options"></select>

    {{selectedOption}}
</div>

Controller

function Controller ($scope) {
    var initialOptions = ['One', 'Two', 'Three'];

    $scope.options = initialOptions;
    $scope.selectedOption = $scope.options[2]; // pick "Three" by default

    $scope.$watch('selectedOption', function( val ) {
        if( val === 'One' ) {
            $scope.options = ['One', 'Three'];
        } else {
            $scope.options = initialOptions;
        }
    });
}
André Dion
  • 21,269
  • 7
  • 56
  • 60