默认选择一个选项
Selecting an option by default
我正在努力处理以下代码。
<body ng-controller="MainCtrl">
<h1>Select something below</h1>
<select id="s1" ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
<h3>The selected item:</h3>
<pre>{{selectedItem | json}}</pre>
<h3>The inner html of the select:</h3>
<pre id="options" class="prettify html"></pre>
</body>
在 js 中
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 3, name: 'blah' }];
$scope.selectedItem = { id: 3, name: 'blah' };
});
默认情况下,我有一个 selected 项目。但它不会在页面加载时显示在 selection 中。
我在下面提供了我的代码link
http://plnkr.co/edit/FlESsL?p=preview
在给定的示例中,下拉列表默认应 select 项目 blah
。
TIA
莫宾
试试这个:
<select id="s1" ng-model="selectedItem" ng-options="item.id as item.name for item in items"></select>
和:
$scope.selectedItem = 3;
您需要做的第一件事是更新您的 angularjs 版本,然后您可以简单地按照 angular select 示例进行操作。
在提供的 link 中,他们使用 track by
来显示正确的对象,我冒昧地编辑了他们的示例 plunker 并添加了您的代码 Here it is!
如您所见,我添加到您的代码中的唯一内容是 track by item.id
在提问之前你有没有经过 - https://docs.angularjs.org/api/ng/directive/ngOptions
只需在您的控制器中进行以下更改 -
$scope.selectedItem = $scope.items[0];
我正在努力处理以下代码。
<body ng-controller="MainCtrl">
<h1>Select something below</h1>
<select id="s1" ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
<h3>The selected item:</h3>
<pre>{{selectedItem | json}}</pre>
<h3>The inner html of the select:</h3>
<pre id="options" class="prettify html"></pre>
</body>
在 js 中
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 3, name: 'blah' }];
$scope.selectedItem = { id: 3, name: 'blah' };
});
默认情况下,我有一个 selected 项目。但它不会在页面加载时显示在 selection 中。
我在下面提供了我的代码link
http://plnkr.co/edit/FlESsL?p=preview
在给定的示例中,下拉列表默认应 select 项目 blah
。
TIA 莫宾
试试这个:
<select id="s1" ng-model="selectedItem" ng-options="item.id as item.name for item in items"></select>
和:
$scope.selectedItem = 3;
您需要做的第一件事是更新您的 angularjs 版本,然后您可以简单地按照 angular select 示例进行操作。
在提供的 link 中,他们使用 track by
来显示正确的对象,我冒昧地编辑了他们的示例 plunker 并添加了您的代码 Here it is!
如您所见,我添加到您的代码中的唯一内容是 track by item.id
在提问之前你有没有经过 - https://docs.angularjs.org/api/ng/directive/ngOptions
只需在您的控制器中进行以下更改 -
$scope.selectedItem = $scope.items[0];