Andrew Mairose
Andrew Mairose

Reputation: 10995

AngularJS ngOptions select default option

I have the following select element that is dynamically populated using angular's ngOptions directive.

<select ng-options="group.parameterGroupId as group.name for group in parameterGroups" 
        ng-change="getParameterGroup(group.parameterGroupId)" 
        ng-model="group.parameterGroupId">
    <option value="">== Choose Group ==</option>
</select>

How can I programatically select the default == Choose Group == option later on, after another value in the dropdown has been selected?

I have tried setting $scope.group.parameterGroupId to null and to "" in my controller, neither of which worked as expected. In both cases, the option that was currently selected stays selected.

Using AngularJS v1.4.3.

Upvotes: 1

Views: 1006

Answers (2)

Andrew Mairose
Andrew Mairose

Reputation: 10995

My problem was that my <select> was included in my page using the ngInclude directive. I discovered that the ngInclude directive actually creates a child scope for the template being included. So, to be able to set the selected group, I needed to make the ng-model of my select accessible from its parent scope.

I ended up incorporating @Italo Ayres's solution as well, to access the default value of my select. Here is my corrected markup, which uses $parent to access the parent scope of my template that my <select> is contained in.

<select ng-options="group.parameterGroupId as group.name for group in parameterGroups" 
        ng-change="getParameterGroup(group.parameterGroupId)" 
        ng-model="$parent.group.parameterGroupId">
    <option value="" ng-model="$parent.defaultGroup">== Choose Group ==</option>
</select>

Then in my controller, I set the selected group to the default like this.

$scope.group {
    parameterGroupId: $scope.defaultGroup
};

Note that I don't use $scope.group.parameterGroupId = $scope.defaultGroup because $scope.group may not be defined when this statement is reached.

Upvotes: 1

Italo Ayres
Italo Ayres

Reputation: 2663

Well, you could atribute some model to your defult option. Take a look:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.options = [
        { desc: 'op1' },
        { desc: 'op2' },
        { desc: 'op3' }
    ]
    $scope.reset = function(){
    	$scope.selected = $scope.default;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <select ng-options="op as op.desc for op in options" ng-model="selected">
    <option value="" ng-model="default">== Choose Group ==</option>
  </select>
    {{selected}}
    
    <br />
    <button ng-click="reset()">Reset!</button>
</div>

This should do the trick.

Upvotes: 2

Related Questions