如何对AngularJS生成的选择列表进行预选?

ran*_*guy 29 javascript angularjs

<select ng-model="team.captain" ng-options="player.name for player in team.players"></select>
Run Code Online (Sandbox Code Playgroud)

这会正确创建选择列表以选择团队队长.但是,默认情况下会选择空白选项.我们如何从列表中预选第一个玩家呢?

<select ng-model="team.captain" ng-options="player.name for player in team.players" class="ng-pristine ng-valid">
  <option value="0">John</option>
  <option value="1">Bobby</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我尝试添加,ng-init="team.captain='0'"但没有帮助.

更新显然这是因为

传递给ng-options的一组选项中不存在ng-model引用的值.

来源:为什么AngularJS在select中包含一个空选项?

但是,问题仍然存在,为什么使用ng-init不起作用?

<select ng-init="team.captain='0'" ng-model="team.captain" ng-options="player.name for player in team.players"></select>
Run Code Online (Sandbox Code Playgroud)

ran*_*guy 32

这是有效的:

<select ng-init="team.captain=team.players[0]" 
        ng-model="team.captain" 
        ng-options="player.name for player in team.players"></select>
Run Code Online (Sandbox Code Playgroud)

什么不起作用:

ng-init="team.captain='0'"
ng-init="team.captain='John'"
Run Code Online (Sandbox Code Playgroud)

我的猜测是Angular不仅仅是对值或标签的简单比较.它可能会比较对象引用.

  • 我应该在我的回答中提到"label"值需要引用数组中的同一个对象.换句话说,这也不会起作用:ng-init ="{name:'John'}" (3认同)

Ger*_*ald 15

这是使用AngularJS初始化下拉菜单的另一种方法.

(关于JS Fiddle的工作示例:http://jsfiddle.net/galeroy/100ho18L/1/)

<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body ng-app="" ng-controller="myController">

    <select 
        ng-model="carSelection"
        ng-options = "x.make for x in cars">
    </select>

    <script>

        function myController($scope) {

            $scope.cars = [
                {"make": "Nissan", "model": "Sentra"},
                {"make": "Honda", "model": "Prelude"},
                {"make": "Toyota", "model": "Prius"}
            ]

            $scope.carSelection = $scope.cars[1]; // this line initializes the drop down menu
        }

    </script>

</body>
Run Code Online (Sandbox Code Playgroud)


Mar*_*cok 5

正如@camus在评论中已经提到的那样,您需要将模型设置为有效的"标签"值(或引用),而不是索引值.这有点奇怪,因为您可以看到HTML中使用的索引值.

Angular在HTML中设置值属性,如下所示:

  • 当使用数组作为数据源时,它将是每次迭代中数组元素的索引;
  • 当使用object作为数据源时,它将是每次迭代中的属性名称.

选择项目时,Angular会根据索引或属性名称在数组/对象中查找正确的条目.