Search code examples
javascriptangularjsangular-uing-switchangular-ui-typeahead

ng-switch does not work with angular-ui typeahead


I am using angular-ui typeahead directive and ng-switch. The objective is when the typeahead input box has been keyed in, a row that starts with "Person info" will appear. Otherwise, it will not appear. The problem now is that this row always appear.

I have created a plunker here. http://plnkr.co/edit/qEaYE6BHjmMewmlheFoh

The relevant code segment is as below; HTML;

<div class='container-fluid' ng-controller="TypeaheadCtrl">
        <h4>Static arrays</h4>
        <!-- <pre>Model: {{selected }}</pre>
        <pre>Model: {{selected.name}} {{selected.id}}</pre> -->
        <div ng-switch="selected.name">
            <div ng-switch-when="" > 
                <BR><BR>                
            </div>
            <div ng-switch-default >              
                <pre>Person info: {{selected.name}} {{selected.id}}</pre> 
            </div>
        </div> 

        <input type="text" ng-model="selected" 
               typeahead="person as person.name for person in person_info | filter:{name:$viewValue} | limitTo:8"                
               class="form-control">        
    </div>

Javascript controller:

var person_info =  [
                        {
                                "name": "Tom",
                                "id": "111"
                        },
                        {
                                "name": "Sam",
                                "id": "222"
                        },
                        {
                                "name": "James",
                                "id": "333"
                        }
                    ];
    $scope.person_info = person_info;

Solution

  • Instead of ng-switch you can use ng-if/ng-show/ng-hide

    here is a code with ng-if

     <div ng-if="selected.name == null" > 
          <BR><BR>                
     </div>
     <div ng-if="selected.name">              
          <pre>Person info: {{selected.name}} {{selected.id}}</pre> 
     </div>
    

    just replace it with ng-switch