AngularJS和Select绑定出现问题,无法加载默认值 [英] Trouble with AngularJS and Select binding not loading default values
问题描述
我在使用< select>
输入并绑定AngluarJS时遇到麻烦。我已经在Plunker上创建了一个最小的工作示例: http://plnkr.co/edit/P4T25RoJrU4mvbBiUJ9S? p = preview 。
I am having trouble with a <select>
input and binding with AngluarJS. I've created a minimum working sample on Plunker: http://plnkr.co/edit/P4T25RoJrU4mvbBiUJ9S?p=preview.
基本问题如下:下拉菜单中的值从未与模型中的值预先选择。
The basic issue is as follows: the value in the dropdown is never pre-selected with the value from my model.
此外,在Angular 1.1.5中, ng-options
似乎在生成的内容中不包含标签 < option>
标记,因此,当您更改选择时,下拉控件不会进行任何更改。
Additionally, in Angular 1.1.5, ng-options
appears to not include a "label" on the generated <option>
tags, so when you change selection the drop down control doesn't register any change.
推荐答案
两个问题:
- 将字符串与字符串进行比较
- 在同一表达式中使用
select as
和track by
时要小心。
- Compare strings to strings
- Be careful when using
select as
andtrack by
in the same expression.
JS
angular.module('defaultValueSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
],
//USE this
selectedOption: '2'
//NOT this
//selectedOption: 2 //This sets the default value
};
}]);
HTML
<!-- remove 'track by option.id' -->
<select name="mySelect" id="mySelect"
ng-options="option.id as option.name for option
in data.availableOptions track by option.id"
ng-model="data.selectedOption">
</select>
从文档中:
在同一表达式中使用
select as
和track by
时要小心。
这将起作用:
<select
ng-options="item as item.label for item in items track by item.id"
ng-model="selected">
</select>
但这不起作用:
<select
ng-options="item.subItem as item.label for item in items track by item.id"
ng-model="selected">
</select>
- AngularJS ng-options
指令API参考
-- AngularJS ng-options
Directive API Reference
这篇关于AngularJS和Select绑定出现问题,无法加载默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!