arjunkm
arjunkm

Reputation: 479

How to pre-select a default option in ng-options using $scope variable

I have a <select> in a form with other fields, like so-

<form class="formCSS">
  <div class="inputs">
   <label class="labelTag">Name *: &nbsp&nbsp</label>
   <select class="inputTag" ng-model="selectedName" 
           ng-options="n.name for n in adminNames"></select>
  </div>
</form>

adminChannels is an object array of this structure {_id:"....", name:"..."}

When I "transitionTo" this state, I pass a name (which exists in adminNames too) like so -

$state.go('schedule',{name:response.name});

I want the said name (accessed using $scope.name) to be pre-selected when this template loads.

I tried something like this -
ng-init = "selectedName=adminNames[adminNames.indexOf(name)]"

I do get the auto-populated drop-down menu but nothing gets selected as default.

I went through all other posts about selecting default options, none of them provide info about pre-selecting using $scope variable.

Please let me know if I've to provide any more info/code. Thanks in advance!

Upvotes: 0

Views: 66

Answers (2)

georgeawg
georgeawg

Reputation: 48948

Use Array.find():

$scope.selectedName = $scope.adminNames.find( x => (x.name == $scope.name));

The find() method returns the value of the first element in the array that satisfies the provided testing function.


Another approach is to use the as clause in the ng-options directive:

<select class="inputTag" ng-model="selectedName" 
        ng-options="n.name as n.name for n in adminNames">
</select>

The DEMO

angular.module("app",[])
.controller("ctrl",function($scope) {
    $scope.adminNames=[
        {name: "fred"},
        {name: "jane"},
        {name: "sally"},
    ];
    $scope.selectedName="jane";
    $scope.find = function(name) {
         return $scope.adminNames.find( x => (x.name == name)); 
    };
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
    <select class="inputTag" ng-model="selectedName" 
            ng-options="n.name as n.name for n in adminNames">
    </select>
    <br>
    object = {{find(selectedName)}}
</body>

For more information, see

Upvotes: 1

arjunkm
arjunkm

Reputation: 479

When I started debugging stage-by-stage, I saw that adminNames[adminNames.indexOf(name)] was "undefined".

So I did this in the controller instead, to find the index of the $scope.name that is received -

var index = $scope.adminNames.map(function(e) { return e.name; }).indexOf($scope.name);

$scope.selectedName = $scope.adminNames[index];

This SO question/answer helped me figure this out.

Upvotes: 0

Related Questions