AngularJS - 选择值返回"?number:x?" 来自范围变量

Sco*_*ger 17 javascript angularjs

尝试获取select元素的初始值而不是填充值,它会添加一个奇怪的字符串,如下图所示:

在此输入图像描述

这是JavaScript代码:

 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
        };
  }
Run Code Online (Sandbox Code Playgroud)

这是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>
Run Code Online (Sandbox Code Playgroud)

这是一个jsbin来演示:http://jsbin.com/EKOpAFI/1/edit

我也试过在这里使用难以置信的文档记录的选择元素,但我不能让它以那种方式工作,无论我的teamId是值,teamName是标签.它总是希望将数组的索引作为值.

任何帮助将不胜感激.

Pas*_*cht 24

select指令真的有点难以理解.这是它如何与ng-options指令一起工作(这是非常强大的!)

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

在使用dev工具检查选择选项时,不要混淆DOM中生成的值.该value属性始终获取其索引.相应的键值对仍然可以根据范围进行评估,因此您只需要更新'ng-model`.

希望这可以帮助!


kmd*_*sax 5

我建议在select元素上使用ng-options,如下所示:

    <select class="small" ng-model="filters.teamIdSelected" ng-options="team.teamId as team.teamName for team in teams"></select>
Run Code Online (Sandbox Code Playgroud)

此外,如果您想要包含"选择团队"选项:

<select class="small" ng-model="filters.teamIdSelected" ng-options="team.teamId as team.teamName for team in teams">
  <option value="">Select Team</options>      
</select>
Run Code Online (Sandbox Code Playgroud)