Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 366
Scotty Bollinger Avatar asked Sep 13 '13 21:09

Scotty Bollinger


2 Answers

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!

like image 92
Pascal Precht Avatar answered Sep 22 '22 16:09

Pascal Precht


I recommend using ng-options on the select element instead, like so:

    <select class="small" ng-model="filters.teamIdSelected" ng-options="team.teamId as team.teamName for team in teams"></select>

Additionally, if you want to include a "Select Team" option:

<select class="small" ng-model="filters.teamIdSelected" ng-options="team.teamId as team.teamName for team in teams">
  <option value="">Select Team</options>      
</select>
like image 34
kmdsax Avatar answered Sep 24 '22 16:09

kmdsax