1

I have a set of drop downs with default values like "Select Team...". These values are not part of the model bound with ng-model since they're meaningless in that context.

The problem is, after a user has selected their values I want to clear the form. I tried setting the bound models to an empty object and null but in neither case do the drop downs revert to their "Select..." default values.

My drop downs look like this:

<select class="form-control input-sm" id="ddlStakeholderTeam"
        ng-change="updateSelectedTeam(selectedTeam);"
        ng-model="selectedTeam"
        ng-options="t as t.TeamName for t in (teamList | filter: filterTeams) track by t.TeamId">
    <option value="" selected disabled hidden>Select Team...</option>
</select>

I want to clear it back to it's default value when the user clicks "Cancel". My ng-click function in the controller looks like this:

$scope.cancelStakeholder = function () {
    $scope.showStakeholderFields = false;
    $scope.selectedDepartment = {};
    $scope.selectedTeam = {}; //also tried setting these to null
    $scope.selectedRep = {};
}

The only thing that's worked is to put in a line like:

document.getElementById('ddlStakeholderTeam').selectedIndex = 0;

Seems like a hack though. Is this the only method that will work?

Legion
  • 3,922
  • 8
  • 51
  • 95
  • bind object reference rather than direct variable. eg: ng-model="obj.selectedTeam" – rupampatel Apr 12 '16 at 19:51
  • @rupampatel2006 `selectedTeam` is attached to `$scope`. `selectedTeam` is an object. Are you saying I need to make a dummy object and attach it to $scope so it's like `$scope.dummy.selectedTeam`? – Legion Apr 12 '16 at 19:54
  • try my friend. selectedTeam becomes property and not object. $scope is special object for angular. When you re-assign property, javascript creates new reference hence it doesn't clear. – rupampatel Apr 12 '16 at 19:56
  • Inserting the dummy object worked, however I don't think it improves things. getElementById is an anachronism in the middle of a bunch of angular code but the intent is clear. I think having a dummy object would both look strange while also not making the intent obvious. Is this a known angular bug? – Legion Apr 12 '16 at 20:07
  • It is not a bug. It is simple fundamental javascript. You are trying to bind variable and resetting it's value which is not gonna work. – rupampatel Apr 12 '16 at 20:11
  • So it's a javascript bug? – Legion Apr 12 '16 at 20:15
  • Refer this: http://stackoverflow.com/a/6605700/6094740 You want to reset select control. You need to reset the value not the reference. – rupampatel Apr 12 '16 at 20:18

0 Answers0