Skip to content
Advertisement

AngularJS – Select value returns “? number:x ?” from scope variable

Trying to get the initial value for a select element and instead of populating the value, it adds a weird string as seen in this image:

enter image description here

Here is the JavaScript code:

 function appCtrl($scope){
        $scope.teams = [
            {teamId: 10, teamName: 'Foo'},
            {teamId: 20, teamName: 'Bar'},
            {teamId: 30, teamName: 'Steve'},
            {teamId: 40, teamName: 'Jobs'},
            {teamId: 50, teamName: 'Macs'}
        ];

        $scope.filters = {
            teamIdSelected: 20
        };
  }

Here is the HTML:

<div ng-app ng-controller="appCtrl"> 
    <select class="small" ng-model="filters.teamIdSelected">
        <option ng-repeat="team in teams" value="{{team.teamId}}">{{team.teamName}}</option>
    </select>

Here is a jsbin to demonstrate: http://jsbin.com/EKOpAFI/1/edit

I also tried using the incredibly poorly documented select element here but I can’t get it to work that way either where my teamId is the value and the teamName is the label. It always wants to put the index of the array as the value.

Any help would be greatly appreciated.

Advertisement

Answer

select directive is really a bit hard to grok. Here’s how it works in conjunction with ng-options directive (which is amazingly powerful!)

<select 
  ng-model="filters.teamIdSelected"
  ng-options="value.teamId as value.teamName for (key, value) in teams"
  ></select>

Don’t get confused with the values generated in the DOM when inspecting the selects options with dev tools. The value attribute always gets its index. Corresponding key values pairs still get evaluated against scope, so all you need is to update ´ng-model`.

Hope this helps!

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement