w2olves
w2olves

Reputation: 2329

Simplest way to Load a dropdown from a Javascript array and Set Selected value using angularjs

I have a simple Javascript Array like this:

var directionArray = [{ id: 'N', text: 'North' },
    { id: 'S', text: 'South' },
{ id: 'E', text: 'East' },
{ id: 'W', text: 'West' }];

I have a select element like this:

<select data-ng-model="bbInventory.DIRECTION_OF_TRAVEL"
                name="travelDirection"
                id="travelDirection"
                class="form-control" style="width: 100%"></select>

The goal is to firstly load the options from the array and then select a value once data is available.

I am drawing a blank, any input will be much appreciated

Upvotes: 0

Views: 46

Answers (2)

Fridjon Gudjohnsen
Fridjon Gudjohnsen

Reputation: 827

A simple setup would be:

$scope.directionArray = [{ id: 'N', text: 'North' },
      { id: 'S', text: 'South' },
      { id: 'E', text: 'East' },
      { id: 'W', text: 'West' }];

And in the html:

<select data-ng-model="bbInventory.DIRECTION_OF_TRAVEL"
        ng-options="item.id as item.text for item in directionArray"
        name="travelDirection"
        id="travelDirection"
        class="form-control" style="width: 100%"></select>

See plunker.

Upvotes: 1

Vanojx1
Vanojx1

Reputation: 5574

use ng-options directive

<select ng-model="bbInventory.DIRECTION_OF_TRAVEL" ng-options="option.text for option in directionArray track by option.id"></select>

then to select an option use

$scope.bbInventory.DIRECTION_OF_TRAVEL = $scope.directionArray[whatyouwantindex];

Upvotes: 1

Related Questions