Danny
Danny

Reputation: 1759

Clearing the $viewValue on Angular UI Bootstrap typeahead

I have a form with fields that are dependent on each other, displayed using UI Bootstrap. Selecting a team from a bootstrap typeahead then populates a list of players that can then be selected in a second typeahead. When the user changes the team I reload the list of players and clear the currently selected player value.

The player options are loaded correctly based on the team, but the issue is that the typeahead is not showing the options when clicked on - I think I might be running afoul of the $viewValue being in a weird state and not matching any of the existing options. If I type a letter that happens to match one of my unseen choices then I get the matching values, and clearing anything that has been typed restores the full list.

I would like the full list to be available on the first click - I suspect I need to reset the $viewValue properly, and I have toyed with trying $setViewValue and $render() on the player model, but have not gotten anywhere.

<div class="options">
Team: <input type="text" 
          name="team"
          placeholder="Select team"
          ng-model="selectedTeam" 
          uib-typeahead="team as team.name for team in league | filter:$viewValue" 
          typeahead-editable="false"
          typeahead-min-length="0"
          class="form-control">
</div>

<div class="options">
<input type="text" 
        name="player"
        placeholder="Select player"
        ng-model="selectedPlayer" 
        uib-typeahead="player as player.name for player in players | filter:$viewValue" 
        typeahead-editable="false"
        typeahead-min-length="0"
        class="form-control">
</div>

The controller that looks for a team change and then resets the player options and selected value:

$scope.$watch('selectedTeam.id', function(newTeamID) {

    // clears any currently selected player ng-model
    $scope.selectedPlayer = null;

    if (!newTeamID)
    {
      return;
    }

    // sets up the list of available players
    $scope.pullPlayers(newTeamID);

});

Full plunkr is available here.

Upvotes: 1

Views: 1424

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59328

To reset players typeahead value from controller you might want something like this:

 $scope.$watch('selectedTeam.id', function(newTeamID) {
    if (!newTeamID)
    {
       $scope.players = [];
       $scope.teamForm.player.$setViewValue('');
       $scope.teamForm.player.$render();
       return;
    }

    // sets up the list of available players
    $scope.pullPlayers(newTeamID);
  });

Here is a forked plunker

Upvotes: 3

Related Questions