0

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

13
  • "using angularjs" in the title, javascript and jquery tags in the question. Which is it? Commented Oct 28, 2015 at 17:02
  • The dropdown can be loaded using pure javascript or jquery. The Selected Option has to be set via Angular. So, all three... Commented Oct 28, 2015 at 17:04
  • @Jesse angular is javascript, hard to fault that one Commented Oct 28, 2015 at 17:13
  • use ng-options to populate the <select>. Commented Oct 28, 2015 at 17:14
  • look at the examples in the angular docs: docs.angularjs.org/api/ng/directive/select Commented Oct 28, 2015 at 17:15

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. I can load json array using the same set up right ?
Sure, it's all just objects :)
1

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];

1 Comment

Thank you. I selected Fridjon's answer as the accepted one simply because of the Plunker and he was a few seconds faster. I believe either of your's or his answer would be helpful to me as well as others who are looking for a similar solution. Thanks again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.